httpclient接口调用

本文提供了一个使用Java发送HTTP Post请求的示例代码。通过HttpClient实现了包含代理认证的过程,并介绍了如何设置请求参数、处理响应结果等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值