public static String sendGetRequest(String url,String encode){
System.out.println("url:=====>>>>>>"+ url);
HttpClient httpclient = null;
GetMethod get = null;
StringBuffer result = new StringBuffer("");
BufferedReader in = null;
try {
httpclient = new HttpClient();
get = new GetMethod(url);
get.setRequestHeader("Content-Type","text/xml");
get.setRequestHeader("charset",encode);
int statuCode = httpclient.executeMethod(get);
if(statuCode==HttpStatus.SC_OK){ //请求成功,返回200
in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),encode)); //将返回的数据读入IO流
String line;
while((line=in.readLine())!=null){
result.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(in!=null){
in.close();
}
if(get!=null){
get.releaseConnection();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("result====>>>"+result);
return result.toString();
}
我用的版本是3.1的,4.5没用过,不过大同小异吧。这里我封装了一个方法,你参考一下。以get方式请求url是请求地址,encode是请求编码,设为utf-8就行,返回值是请求到的内容。
附件中是源代码,感兴趣可以看一下。