您的位置:首页 > 理论基础 > 计算机网络

使用httpclient 4.4实现需要basic auth认证的http请求

2015-06-25 00:00 621 查看
摘要: 使用httpclient 4.4实现需要basic auth认证的http请求

public class HttpHelper {
private final static HttpHelper instance = new HttpHelper();
private HttpHelper() {

}

public final static HttpHelper getInstnace() {
return instance;
}

/**
*
* @param host 服务主机地址如 apiv2.sewcloud.com
* @param port 服务端口
* @param uri 请求的uri如/api/sendmail
* @param postData 提交的请求数据
* @param username 用户名
* @param password 密码
* @param timeout 超时时间(单位为毫秒)
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
public String postBasicAuth(String host, int port, String uri, String postData, String username, String password,
int timeout) throws ClientProtocolException, IOException,
KeyManagementException, NoSuchAlgorithmException {
String deliverResponse = null;
CloseableHttpClient httpclient = HttpClients.createDefault();

HttpHost targetHost = new HttpHost(host, port, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(),
targetHost.getPort()), new UsernamePasswordCredentials(
username, password));

// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);

// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpPost httppost = new HttpPost(uri);
//设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout).setSocketTimeout(timeout).build();
httppost.setConfig(requestConfig);
StringEntity postentity = new StringEntity(postData,"utf-8");
postentity.setContentType("application/json");
postentity.setContentEncoding("utf-8");
//httppost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
httppost.setEntity(postentity);
CloseableHttpResponse response = null;

try {
response = httpclient.execute(targetHost, httppost, context);

HttpEntity entity = response.getEntity();
deliverResponse = EntityUtils.toString(entity);

httpclient.close();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return deliverResponse;
}
}

测试代码

HttpHelper httpHelper = HttpHelper.getInstnace();
String resp = this.httpHelper.postBasicAuth("apiv2.sewcloud.com", 80, "/api/sendmail",  builder.toString(), "sewcloud", "sewcloud6688" ,10000);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  httpclient basic auth