public class HttpRequest { @Test public void httpPost() throws IOException { //创建client CloseableHttpClient client=HttpClients.createDefault(); //创建 HttpPost HttpPost post=new HttpPost("http://www.httpbin.org/post"); //设置请求头 post.setHeader("accept","application/json"); post.setHeader("Referer","http://www.httpbin.org/"); //设置请求参数 StringEntity se=new StringEntity("this is request param", ContentType.APPLICATION_JSON); post.setEntity(se); //获取响应 CloseableHttpResponse response=client.execute(post); HttpEntity entity=response.getEntity(); String result=EntityUtils.toString(entity); //关闭流和连接 EntityUtils.consume(entity); response.close(); //解析result JSONObject jsonObject=JSON.parseObject(result); System.out.println(jsonObject.getString("data")); } }
结果
this is request param
其中设置请求参数有两种方法
1.使用 StringEntity ,StringEntity 的更多参数查看源码可知
StringEntity se=new StringEntity("this is request param", ContentType.APPLICATION_JSON); post.setEntity(se);
2. 使用 UrlEncodedFormEntity,UrlEncodedFormEntity 的更多参数查看源码可知
NameValuePair nvp=new BasicNameValuePair("requestParam","this is request param"); List<NameValuePair> nvps=new ArrayList<>(); nvps.add(nvp); UrlEncodedFormEntity param=new UrlEncodedFormEntity(nvps, Charset.defaultCharset()); post.setEntity(param);