package httpclient.httpclient; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public void testPost() { //1.建立客戶端訪問服務器的httpclient對象 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //2.定義請求的url String url = "https://XXX.XXX.com/NC1000001"; //3.以請求的鏈接地址建立get/post請求對象 HttpPost post = new HttpPost(url); //若是有header請求,添加header請求 post.addHeader("x-api-key", "XXX"); post.addHeader("x-lang", "en-US"); try { //4.向服務器發送請求,並獲取返回數據 CloseableHttpResponse response = httpClient.execute(post); //獲取返回的全部headers Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println(header); } //獲取返回的狀態 int status = response.getStatusLine().getStatusCode(); System.out.println(status); //獲取HttpEntity消息載體對象 HttpEntity entity = response.getEntity(); // EntityUtils中的toString()方法轉換服務器的響應數據 String str = EntityUtils.toString(entity, "utf-8"); System.out.println("服務器的響應是:" + str); //5.關閉鏈接 httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { HttpClientUtil util = new HttpClientUtil(); util.testPost(); } }
httpClientRequestjava
package modeHttp; import java.util.HashMap; import java.util.Map; public class HttpClientRequest { private String url; private Map<String,String> headers = new HashMap<String,String>(); private String body; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
HttpClientResponapache
package modeHttp; import java.util.HashMap; import java.util.Map; public class HttpClientResponse { private String statusCode; private Map<String,String> header = new HashMap<String,String>(); private String body; public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public Map<String, String> getHeader() { return header; } public void setHeader(Map<String, String> header) { this.header = header; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
HttpHelperapi
package Utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import modeHttp.HttpClientResponse; import org.apache.http.Header; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.testng.log4testng.Logger; import Http.HttpClientRequest; public class HttpHelper { HttpClientRequest httpClientRequest; CloseableHttpClient httpClient ; public CloseableHttpClient getHttpClient() { return httpClient; } public void setHttpClient(CloseableHttpClient httpClient) { this.httpClient = httpClient; } private static Logger logger = Logger.getLogger(HttpHelper.class); /* * 獲取連接 */ public void init() { httpClient = HttpClientBuilder.create().build(); } /* * 關閉連接 */ public void close() { try { httpClient.close(); } catch (IOException e) { logger.error(""); logger.error(e.getMessage()); } } /* * 調用接口 */ public HttpClientResponse sendrequest(HttpClientRequest httpClientRequest,HttpRequestBase httpRequestBase) { String url = httpClientRequest.getUrl(); CloseableHttpResponse response = null; String encodingofBody = "ISO-8859-1"; HttpClientResponse httpClientResponse = null; Map<String,String> headers = httpClientRequest.getHeaders(); //設置header,包含Conent-Type for(String header:headers.keySet()) { httpRequestBase.setHeader(header, headers.get(header)); //獲取編碼方式 if(header.toLowerCase().equals("Conent-Type")) { if(headers.get(header).split(";").length >= 2) { encodingofBody = headers.get(header).split(";")[1].split("=")[1]; } } } //斷定是否有方法是否有body,再設置body if(httpRequestBase instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) httpRequestBase).setEntity(new StringEntity(httpClientRequest.getBody(),encodingofBody)); } try { response = httpClient.execute(httpRequestBase); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } httpClientResponse.setBody(response.getEntity().toString()); Header[] headerResponses = response.getAllHeaders(); Map<String,String> headerResponseMap = new HashMap<String,String>(); for(Header headerResponse:headerResponses) { headerResponseMap.put(headerResponse.getName(),headerResponse.getValue()); } httpClientResponse.setHeader(headerResponseMap); httpClientResponse.setStatusCode(String.valueOf(response.getStatusLine().getStatusCode())); return httpClientResponse; } public HttpClientResponse doGet(HttpClientRequest httpClientRequest) { HttpHelper helper = new HttpHelper(); HttpClientResponse httpClientResponse; helper.init(); String url = httpClientRequest.getUrl(); HttpGet get = new HttpGet(url); httpClientResponse = helper.sendrequest(httpClientRequest, get); helper.close(); return httpClientResponse; } public String fromeUrl(String url,Map<String,String> params) { String result; StringBuffer urlTest = new StringBuffer(url); urlTest.append("?"); for(String param:params.keySet()) { urlTest.append(param).append("=").append(params.get(param)).append("&"); } return result = urlTest.toString().substring(0,urlTest.length()-1); } }