您好,登錄后才能下訂單哦!
這篇文章給大家介紹java中HttpsPost和CloseableHttpClient如何使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
//請求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(); //設(shè)置傳入?yún)?shù) 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("請求第三方異常,狀態(tài)碼{},地址{}",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(); //設(shè)置傳入?yún)?shù) 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())); } } //設(shè)置參數(shù)到請求對象中 httpGet.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); //裝填參數(shù) 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("請求第三方異常,狀態(tài)碼{},地址{}",statusCode,url); } return respContent; }
關(guān)于java中HttpsPost和CloseableHttpClient如何使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。