1. 程式人生 > 實用技巧 >HttpClient 通過 httpPost傳送資料模板

HttpClient 通過 httpPost傳送資料模板

     String url = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(data), "UTF-8");
        httpPost.setEntity(stringEntity);
        httpPost.setHeader(
"Content-Type", "application/json;charset=utf8"); CloseableHttpResponse response = null; try { // 由客戶端執行(傳送)Post請求 response = httpClient.execute(httpPost); // 從響應模型中獲取響應實體 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null
) { log.info("響應內容:" + EntityUtils.toString(responseEntity)); } } catch (IOException e) { e.printStackTrace(); } finally { try { // 釋放資源 if (httpClient != null) { httpClient.close(); }
if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } }