導出mven依賴java
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
package testhttpclient.testhttpclient; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientComm { /** * 客戶端總成 */ protected CloseableHttpClient httpclient; /** * cookie信息 */ protected Set<String>cookies; /** * get方法 */ protected HttpGet httpget; /** * post方法 */ protected HttpPost httppost; /** * 代理 */ protected HttpHost proxy; /** * 設置默認延遲時間 */ protected RequestConfig requestconfig; /** * 返回存儲數據map */ protected Map<String,String>resultmap; /** * 響應狀態 */ public final String HTTPSTATUS="status"; /** * 返回數據結果 */ public final String HTTPRESULT="httpresult"; /** * 初始化客戶端 */ public HttpClientComm() { httpclient=HttpClients.createDefault(); requestconfig=RequestConfig.custom().setConnectionRequestTimeout(10*1000).setSocketTimeout(10*1000).build(); cookies=new HashSet<String>(16); } /** * 初始化請求,設置請求時間 * @param millistimeout */ public HttpClientComm(int millistimeout) { httpclient=HttpClients.createDefault(); requestconfig=RequestConfig.custom().setConnectionRequestTimeout(10*1000).setSocketTimeout(10*1000).build(); cookies=new HashSet<String>(16); } /** * 設置代理 * * @Data:上午11:02:43 * @Package:testhttpclient.testhttpclient * @Return:void * @Auth:diao */ public void setProxy(String Address,int port) { proxy=new HttpHost(Address, port); requestconfig=RequestConfig.custom().setProxy(proxy).build(); } /** * 釋放請求資源 * * @Data:上午11:03:27 * @Package:testhttpclient.testhttpclient * @Return:void * @Auth:diao */ public void close() { if(cookies!=null) { cookies=null; } if(proxy!=null) { proxy=null; } if(resultmap!=null) { resultmap=null; } if(httpget!=null) { httpget.releaseConnection(); } if(httppost!=null) { httppost.releaseConnection(); } if(httpclient!=null) { try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { httpclient=null; } } } /** * * get請求傳遞的鏈接,請求頭 * @Data:上午11:15:10 * @Package:testhttpclient.testhttpclient * @Return:Map<String,String> * @Auth:diao */ public Map<String,String>get(String url,Map<String,String>headers){ httpget=new HttpGet(url); httpget.setConfig(requestconfig); headers.forEach((a,b)->{ httpget.addHeader(a, b); }); httpget.addHeader("cookie",cookies.toString().substring(1,cookies.toString().length()-1)); CloseableHttpResponse respose=null; try { respose=httpclient.execute(httpget); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return getResData(respose, httpget); } /** * post請求方式 * * @Data:下午2:01:15 * @Package:testhttpclient.testhttpclient * @Return:Map<String,String> * @Auth:diao */ public Map<String,String>post(String url,Map<String,String>headers,Map<String,String>params,String charset) throws UnsupportedEncodingException { //設置請求方法及鏈接信息 httppost=new HttpPost(url); //設置請求參數 httppost.setConfig(requestconfig); //設置請求頭 headers.forEach((a,b)->{ httpget.addHeader(a, b); }); BasicCookieStore cookie=new BasicCookieStore(); HttpClients.custom().setDefaultCookieStore(cookie).build(); httppost.addHeader("cookie",cookies.toString().substring(1,cookies.toString().length()-1)); List<NameValuePair>pairs=null; if(params!=null&&!params.isEmpty()) { pairs=new ArrayList<NameValuePair>(params.size()); for(String key:params.keySet()) { pairs.add(new BasicNameValuePair(key,params.get(key).toString())); } } if(pairs!=null&&pairs.size()>0) { httppost.setEntity(new UrlEncodedFormEntity(pairs,charset)); } //執行請求 HttpResponse response=null; try { response=httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return getResData(response, httppost); } /** * 處理http結果請求 * * @Data:下午1:42:28 * @Package:testhttpclient.testhttpclient * @Return:Map<String,String> * @Auth:diao */ public Map<String,String> getResData(HttpResponse response,HttpRequestBase requestbase) { int status=405; if(response!=null) { status=response.getStatusLine().getStatusCode(); for(Header header:response.getAllHeaders()) { if("Set-Cookie".equalsIgnoreCase(header.getName())) { cookies.add(header.getValue()); } } } resultmap=new HashMap<>(16); resultmap.put(HTTPRESULT,status+""); resultmap.put(HTTPRESULT, null); if(status!=HttpStatusEnum.OK.code()) { requestbase.abort(); }else { HttpEntity entity= response.getEntity(); if(entity!=null) { try { String data=EntityUtils.toString(entity,"utf-8"); String start="[",end="]"; if(data.startsWith(start)) { data=data.substring(1); } if(data.endsWith(end)) { data=data.substring(0,data.length()-1); } data=data.replaceAll("\\\\t|\\\\n|\\r\\n",""); data=data.replaceAll("\\\\/","/"); data=decodeUnicode(data); resultmap.put(HTTPRESULT, data); //關閉流 EntityUtils.consume(entity); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } response=null; } } return resultmap; } /** * unicode轉中文 * * @Data:下午1:44:16 * @Package:testhttpclient.testhttpclient * @Return:String * @Auth:diao */ public static String decodeUnicode(final String dataStr) { int start = 0; int end = 0; final StringBuffer buffer = new StringBuffer(); while (start > -1) { end = dataStr.indexOf("\\u", start + 2); String charStr = ""; if (end == -1) { charStr = dataStr.substring(start + 2, dataStr.length()); } else { charStr = dataStr.substring(start + 2, end); } // 16進制parse整形字符串。 char letter = (char) Integer.parseInt(charStr, 16); buffer.append(new Character(letter).toString()); start = end; } return buffer.toString(); } /** * 獲取請求頭 * * @Data:下午1:44:16 * @Package:testhttpclient.testhttpclient * @Return:String * @Auth:diao */ public Map<String,String>getCommHeader(){ Map<String,String>headers=new HashMap<String, String>(16); headers.put("User-Agent","Mozilla/5.0(Window NT 6.1; WOW64; rv:58.0) Gecko/20100101 Firfox/58.0"); headers.put("Accept","application/json,text/plain,*/*"); headers.put("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"); headers.put("Accept-Encoding","gzip,deflate"); headers.put("Connection","keep-alive"); return headers; } public void test(String ip,int port,String jobid) { String url=String.format("http://%s:%d/jobs/%s/yarn-cancel",ip,port,jobid); HttpClientComm httpclient=new HttpClientComm(); Map<String,String>header=new HashMap<String, String>(16); header.put("Host",ip+":"+port); header.put("Referer","http://"+ip+":"+port); Map<String,String>Resultmap=httpclient.get(url, header); String httpstatus=Resultmap.get(httpclient.HTTPSTATUS); String resultmap=Resultmap.get(httpclient.HTTPRESULT); if(httpstatus.isEmpty()&&HttpStatusEnum.ACCEPTED.code()==Integer.parseInt(httpstatus)) { //json解析 } } }
全部狀態枚舉類apache
package testhttpclient.testhttpclient; /** * * @author sdzw * */ public enum HttpStatusEnum { /** * 請繼續發送請求的剩餘部分 */ CONTINUE(100, "Continue", "請繼續發送請求的剩餘部分"), SWITCHING_PROTOCOLS(101, "Switching Protocols", "協議切換"), PROCESSING(102, "Processing", "請求將繼續執行"), // for 103 https://news.ycombinator.com/item?id=15590049 CHECKPOINT(103, "Checkpoint", "能夠預加載"), OK(200, "OK", "請求已經成功處理"), CREATED(201, "Created", "請求已經成功處理,並建立了資源"), ACCEPTED(202, "Accepted", "請求已經接受,等待執行"), NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information", "請求已經成功處理,可是信息不是原始的"), NO_CONTENT(204, "No Content", "請求已經成功處理,沒有內容須要返回"), RESET_CONTENT(205, "Reset Content", "請求已經成功處理,請重置視圖"), PARTIAL_CONTENT(206, "Partial Content", "部分Get請求已經成功處理"), MULTI_STATUS(207, "Multi-Status", "請求已經成功處理,將返回XML消息體"), ALREADY_REPORTED(208, "Already Reported", "請求已經成功處理,一個DAV的綁定成員被前一個請求枚舉,而且沒有被再一次包括"), IM_USED(226, "IM Used", "請求已經成功處理,將響應一個或者多個實例"), MULTIPLE_CHOICES(300, "Multiple Choices", "提供可供選擇的回饋"), MOVED_PERMANENTLY(301, "Moved Permanently", "請求的資源已經永久轉移"), FOUND(302, "Found", "請從新發送請求"), // MOVED_TEMPORARILY(302, "Moved Temporarily", "") 已通過時 SEE_OTHER(303, "See Other", "請以Get方式請求另外一個URI"), NOT_MODIFIED(304, "Not Modified", "資源未改變"), USE_PROXY(305, "Use Proxy", "請經過Location域中的代理進行訪問"), // 306在新版本的規範中被棄用 TEMPORARY_REDIRECT(307, "Temporary Redirect", "請求的資源臨時從不一樣的URI響應請求"), RESUME_INCOMPLETE(308, "Resume Incomplete", "請求的資源已經永久轉移"), BAD_REQUEST(400, "Bad Request", "請求錯誤,請修正請求"), UNAUTHORIZED(401, "Unauthorized", "沒有被受權或者受權已經失效"), PAYMENT_REQUIRED(402, "Payment Required", "預留狀態"), FORBIDDEN(403, "Forbidden", "請求被理解,可是拒絕執行"), NOT_FOUND(404, "Not Found", "資源未找到"), METHOD_NOT_ALLOWED(405, "Method Not Allowed", "請求方法不容許被執行"), NOT_ACCEPTABLE(406, "Not Acceptable", "請求的資源不知足請求者要求"), PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "請經過代理進行身份驗證"), REQUEST_TIMEOUT(408, "Request Timeout", "請求超時"), CONFLICT(409, "Conflict", "請求衝突"), GONE(410, "Gone", "請求的資源不可用"), LENGTH_REQUIRED(411, "Length Required", "Content-Length未定義"), PRECONDITION_FAILED(412, "Precondition Failed", "不知足請求的先決條件"), REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large", "請求發送的實體太大"), REQUEST_URI_TOO_LONG(414, "Request-URI Too Long", "請求的URI超長"), UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "請求發送的實體類型不受支持"), REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable", "Range指定的範圍與當前資源可用範圍不一致"), EXPECTATION_FAILED(417, "Expectation Failed", "請求頭Expect中指定的預期內容沒法被服務器知足"), LOCKED(423, "Locked", "當前資源被鎖定"), FAILED_DEPENDENCY(424, "Failed Dependency", "因爲以前的請求發生錯誤,致使當前請求失敗"), UPGRADE_REQUIRED(426, "Upgrade Required", "客戶端須要切換到TLS1.0"), PRECONDITION_REQUIRED(428, "Precondition Required", "請求須要提供前置條件"), TOO_MANY_REQUESTS(429, "Too Many Requests", "請求過多"), REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "請求頭超大,拒絕請求"), INTERNAL_SERVER_ERROR(500, "Internal Server Error", "服務器內部錯誤"), NOT_IMPLEMENTED(501, "Not Implemented", "服務器不支持當前請求的部分功能"), BAD_GATEWAY(502, "Bad Gateway", "響應無效"), SERVICE_UNAVAILABLE(503, "Service Unavailable", "服務器維護或者過載,拒絕服務"), GATEWAY_TIMEOUT(504, "Gateway Timeout", "上游服務器超時"), HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported", "不支持的HTTP版本"), VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "服務器內部配置錯誤"), INSUFFICIENT_STORAGE(507, "Insufficient Storage", "服務器沒法完成存儲請求所需的內容"), LOOP_DETECTED(508, "Loop Detected", "服務器處理請求時發現死循環"), BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded", "服務器達到帶寬限制"), NOT_EXTENDED(510, "Not Extended", "獲取資源所需的策略沒有被知足"), NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "須要進行網絡受權"); /** * 狀態碼 */ private final int code; /** * 中文含義 */ private final String reasonPhraseUS; /** * 英文含義 */ private final String reasonPhraseCN; /** * 某個數字表明的錯誤類型 */ private static final int INFORMATIONAL = 1, SUCCESSFUL = 2, REDIRECTION = 3, CLIENT_ERROR = 4, SERVER_ERROR = 5; HttpStatusEnum(int code, String reasonPhraseUS, String reasonPhraseCN) { this.code = code; this.reasonPhraseUS = reasonPhraseUS; this.reasonPhraseCN = reasonPhraseCN; } public int code() { return code; } public String reasonPhraseUS() { return reasonPhraseUS; } public String reasonPhraseCN() { return reasonPhraseCN; } public static HttpStatusEnum valueOf(int code) { for (HttpStatusEnum httpStatus : values()) { if (httpStatus.code() == code) { return httpStatus; } } throw new IllegalArgumentException("No matching constant for [" + code + "]"); } public boolean is1xxInformational() { return type() == INFORMATIONAL; } public boolean is2xxSuccessful() { return type() == SUCCESSFUL; } public boolean is3xxRedirection() { return type() == REDIRECTION; } public boolean is4xxClientError() { return type() == CLIENT_ERROR; } public boolean is5xxServerError() { return type() == SERVER_ERROR; } private int type() { return (int) code / 100; } }