【二】HttpClient4.3.1 HttpPost

使用HttpClient Post提交数据,详细代码注释

[java]  view plain copy
  1. public static void main(String args[]) {  
  2.        //创建HttpClientBuilder  
  3.        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
  4.        //HttpClient  
  5.        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
  6.   
  7.        HttpPost httpPost = new HttpPost("http://tutor.sturgeon.mopaas.com/tutor/search");  
  8.        httpPost.setConfig(DEFAULT);  
  9.        // 创建参数队列  
  10.        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  11.        formparams.add(new BasicNameValuePair("searchText""英语"));  
  12.   
  13.        UrlEncodedFormEntity entity;  
  14.        try {  
  15.            entity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  16.            httpPost.setEntity(entity);  
  17.   
  18.            HttpResponse httpResponse;  
  19.            //post请求  
  20.            httpResponse = closeableHttpClient.execute(httpPost);  
  21.   
  22.            //getEntity()  
  23.            HttpEntity httpEntity = httpResponse.getEntity();  
  24.            if (httpEntity != null) {  
  25.                //打印响应内容  
  26.                System.out.println("response:" + EntityUtils.toString(httpEntity, "UTF-8"));  
  27.            }  
  28.            //释放资源  
  29.            closeableHttpClient.close();  
  30.        } catch (Exception e) {  
  31.            e.printStackTrace();  
  32.        }  
  33.   
  34.    }  

你可能感兴趣的:(【二】HttpClient4.3.1 HttpPost)