1. 程式人生 > >【二】HttpClient4.3.1 HttpPost

【二】HttpClient4.3.1 HttpPost

使用HttpClient Post提交資料,詳細程式碼註釋

 public static void main(String args[]) {
        //建立HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

        HttpPost httpPost = new HttpPost("http://tutor.sturgeon.mopaas.com/tutor/search");
        httpPost.setConfig(DEFAULT);
        // 建立引數佇列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("searchText", "英語"));

        UrlEncodedFormEntity entity;
        try {
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(entity);

            HttpResponse httpResponse;
            //post請求
            httpResponse = closeableHttpClient.execute(httpPost);

            //getEntity()
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                //列印響應內容
                System.out.println("response:" + EntityUtils.toString(httpEntity, "UTF-8"));
            }
            //釋放資源
            closeableHttpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }