package com.yyb.shopping.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
/**
* 此处主要介绍获取返回值
* @param args
* @throws ClientProtocolException
* @throws IOException
*/
public static void main(String[] args) throws ClientProtocolException, IOException {
// 创建客戶端
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// Get方法 如果是POST方法,則為HttpPost
HttpGet httpget = new HttpGet("http://localhost:8080/Shopping/login/addUser");
System.out.println("Executing request " + httpget.getRequestLine());
// 创建一個返回值Handle
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
// 获取请求状态
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
}
/**
* 此处主要做鉴权
* @throws Exception
*/
public void ClientAuthentication() throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
需要依赖的jar包如下:
官网下载地址:http://hc.apache.org/downloads.cgi
commons-codec-1.9.jar
commons-logging-1.2.jar
fluent-hc-4.5.3.jar
httpclient-4.5.3.jar
httpclient-cache-4.5.3.jar
httpclient-win-4.5.3.jar
httpcore-4.4.6.jar
httpmime-4.5.3.jar
jna-4.1.0.jar
jna-platform-4.1.0.jar