httpClient POST 請求
阿新 • • 發佈:2019-03-08
getent resp create asi ace cep ktr finally int
public static String doPostJson(String url,Map<String,String> map) { // 創建Httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 創建Http Post請求 HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(map!=null){ for (Entry<String, String> entry : map.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //設置參數到請求對象中 httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); // 創建請求內容 // StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); // httpPost.setEntity(entity); // 執行http請求 response = httpClient.execute(httpPost); HttpEntity httpEntity = response.getEntity(); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (Exception e) { e.printStackTrace(); } } return resultString; }
httpClient POST 請求