httpclient接口调用

来源:互联网 发布:深圳二手房交易数据 编辑:程序博客网 时间:2024/04/23 21:41
public static String doPost(String url, NameValuePair[] params,
String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();

String proxyHost = "192.168.19.9";
int proxyPort = 80;
String userName = "yellowpage\\yellowpage_jpsc";
String password = "abcd_123";

/*
client.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(userName, password));
HttpHost proxy = new HttpHost(proxyHost,proxyPort);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
*/


client.getHostConfiguration().setProxy(proxyHost, proxyPort);
client.getParams().setAuthenticationPreemptive(true);
//如果代理需要密码验证,这里设置用户名密码
client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName,password));

PostMethod method = new PostMethod(url);
// 设置Http Post数据
if (params != null) {
// HttpMethodParams p = new HttpMethodParams();
// for (Map.Entry<String, String> entry : params.entrySet()) {
// p.setParameter(entry.getKey(), entry.getValue());
//
// }
method.setRequestBody(params);
}
try {
client.executeMethod(method);
log.info("http response status code: " + method.getStatusCode());
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(method.getResponseBodyAsStream(),
charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
log.error(
"request url exception: " + url + " params: {" + params != null ? params
.toString() : "" + "}", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
0 0
原创粉丝点击