get方式获取数据,贴上代码
/**
* GET的方式请求
* @createDate: Apr 2, 2011 5:58:03 PM
* @param http_url
* @param isProxy
* @return
*/
public String doGet(String http_url, boolean isProxy) {
HttpMethod method = null;
try {
URI uri = new URI(http_url, true);
HttpClient client = new HttpClient();
HostConfiguration hcfg = new HostConfiguration();
hcfg.setHost(uri);
client.setHostConfiguration(hcfg);
if (isProxy)
setProxy(client);
// 参数验证
client.getParams().setAuthenticationPreemptive(true);
// GET请求方式
method = new GetMethod(http_url);
client.executeMethod(method);
System.out.println("state:" + method.getStatusLine());
return method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
POST方式获取数据,代码:
/**
* POST方式提交数据
* @createDate: Apr 2, 2011 5:58:03 PM
* @param http_url
* @param isProxy
* @return
*/
public String doPost(String http_url, Map<String, String> paramaters,
boolean isProxy) {
PostMethod method = null;
try {
URI uri = new URI(http_url, true);
HttpClient client = new HttpClient();
HostConfiguration cf = new HostConfiguration();
cf.setHost(uri);
client.setHostConfiguration(cf);
if (isProxy)
setProxy(client);
client.getParams().setAuthenticationPreemptive(true);
method = new PostMethod(http_url);
//添加参数
if(paramaters!=null){
Iterator<Entry<String, String>> its = paramaters.entrySet().iterator();
while (its.hasNext()) {
Entry<String, String> e = its.next();
method.addParameter(e.getKey(), e.getValue());
}
}
client.executeMethod(method);
// 打印服务器返回的状态
System.out.println(method.getStatusLine());
// 输出返回的信息
return method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放连接
if(method!=null)
method.releaseConnection();
}
return null;
}
方法中使用到的代理,代码
/**
* 设置代理
* @createDate: Apr 2, 2011 6:03:30 PM
* @param client
*/
private void setProxy(HttpClient client) {
// 设置代理
client.getHostConfiguration().setProxy(HTTP_HOST, HTTP_PORT);
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(HTTP_USER, HTTP_PWD));
}
附上测试代码
//get测试代码
String str_url = "http://mingnjintian-163-com.iteye.com/blog/985124";
new RequestManager().doGet(str_url,true);
//post测试代码
str_url = "http://mingnjintian-163-com.iteye.com/blog/985124";
new RequestManager().doPost(str_url, new HashMap<String, String>(),true);