您好,登錄后才能下訂單哦!
這篇文章給大家介紹java中HttpsPost和CloseableHttpClient如何使用,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
//請求json public static String HttpsPost(String url, Map<String, Object> param) throws Exception{ String respContent =""; String restServiceURL = url; System.out.println(restServiceURL); CloseableHttpClient client = HttpClients.createDefault(); //設置傳入參數 StringEntity entity = new StringEntity(JSONObject.toJSONString(param), "utf-8"); HttpPost httpGet = new HttpPost(restServiceURL); httpGet.addHeader("Content-Type","application/json;charset=UTF-8"); httpGet.setEntity(entity); HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); if ( 200==statusCode ) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "utf-8"); }else { log.error("請求第三方異常,狀態碼{},地址{}",statusCode,url); } return respContent; }
/** * http請求 application/x-www-form-urlencoded */ public static String HttpsPostXw(String url, Map<String, String> param) throws Exception{ String respContent =""; String restServiceURL = url; CloseableHttpClient client = HttpClients.createDefault(); //設置傳入參數 HttpPost httpGet = new HttpPost(restServiceURL); httpGet.setHeader("Content-type", "application/x-www-form-urlencoded"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(param!=null){ for (Map.Entry<String, String> entry : param.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //設置參數到請求對象中 httpGet.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); //裝填參數 if(param!=null){ for (Map.Entry<String, String> entry : param.entrySet()) { httpGet.setHeader(entry.getKey(),entry.getValue()); } } HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); if ( 200==statusCode ) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "utf-8"); }else { log.error("請求第三方異常,狀態碼{},地址{}",statusCode,url); } return respContent; }
關于java中HttpsPost和CloseableHttpClient如何使用就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。