【实例1.最最最简洁的POST请求】
@Test public void test1() throws Exception{ //1.创建Htpclient实例(可关闭 Closeable) CloseableHttpClient httpClient =HttpClients.createDefault(); //2.创建一个HTTP POST请求的HttpPost实例 HttpPost httpPost=new HttpPost("http://www.baidu.com"); //3.执行请求,获得响应的实例 CloseableHttpResponse response=httpClient.execute(httpPost); response.close(); httpClient.close(); }
【实例2.带Entity的Post请求】
@Test public void test2() throws Exception{ //1.创建Htpclient实例(可关闭 Closeable) CloseableHttpClient httpClient =HttpClients.createDefault(); //2.创建一个HTTP POST请求的HttpPost实例 HttpPost httpPost=new HttpPost("http://www.baidu.com"); //设置POST请求的参数 List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("startDate", "2016-02-10")); params.add(new BasicNameValuePair("endDate", "2016-07-04")); HttpEntity urlEntity=new UrlEncodedFormEntity(params,"UTF-8"); //添加参数至Post请求中 httpPost.setEntity(urlEntity); //3.执行请求,获得响应的实例 CloseableHttpResponse response=httpClient.execute(httpPost); response.close(); httpClient.close(); }
【实例3.设置代理使用Fiddler抓取对应的Entity】
@Test public void testRequestConfigPost() throws ClientProtocolException, IOException{ CloseableHttpClient httpclient=HttpClients.createDefault(); HttpPost httpPost=new HttpPost("http://www.baidu.com"); /**设置请求和传输的超时时间**/ RequestConfig.Builder builder=RequestConfig.custom() .setConnectionRequestTimeout(500) .setConnectTimeout(500) .setSocketTimeout(500); String proxy="127.0.0.1:8888"; builder.setProxy(HttpHost.create(proxy)); //设置代理 RequestConfig requestConfig=builder.build(); httpPost.setConfig(requestConfig); //将配置requestConfig设置到HttpGet请求中 //设置POST请求的参数 List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("startDate", "2016-02-10")); params.add(new BasicNameValuePair("endDate", "2016-07-04")); HttpEntity urlEntity=new UrlEncodedFormEntity(params,"UTF-8"); //添加参数至Post请求中 httpPost.setEntity(urlEntity); CloseableHttpResponse response=httpclient.execute(httpPost); response.close(); httpclient.close(); }
[ 使用Fiddler抓取结果 ]