使用httpClient模拟http请求
在很多场景下都需要用到java代码来发送http请求:如和短信后台接口的数据发送,发送数据到微信后台接口中;
这里以apache下的httpClient类来模拟http请求:以get和Post请求为例 分别包含同步和异步请求:
首先例子中的代码用的是maven构建的一个简单的java项目:
同步请求所用到的包是:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
异步请求用到的包是:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1.2</version> </dependency>
这个实例中只需要导入这两个类库即可,如果你希望用单元测试,也可导入junit的jar包:
以下是代码部分:
1:同步get方式的请求 其中 uri 是请求的地址如:http://www.baidu.com
主要http不能省略,否则会报 没有指明协议 的错误 如果需要带数据 则以uri?a=sss 形式即可
public void doGet() throws ClientProtocolException, IOException{ //创建CloseableHttpClient HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); //执行 HttpUriRequest httpGet = new HttpGet(uri); CloseableHttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String entityStr= EntityUtils.toString(entity,"utf-8"); System.out.println(entityStr); } // System.out.println(response.toString()); }
2:同步post请求方式: 请求中需要带的数据通过
httpPost.setEntity(new StringEntity("beppe", "UTF-8"));的方式,
如果需要带的数据是对象的形式,则转化为json字符串格式
public void doPost() throws ClientProtocolException, IOException{ HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpPost httpPost= new HttpPost(uri); httpPost.setEntity(new StringEntity("beppe", "UTF-8")); CloseableHttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity!=null){ String entityStr= EntityUtils.toString(entity,"utf-8"); System.out.println(entityStr); } // System.out.println(response.toString()); }
3:异步get请求:
public void doGetAsyn() throws InterruptedException, ExecutionException{ CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); //开启httpclient httpclient.start(); //开始执行 HttpGet httpGet = new HttpGet(uri); Future<HttpResponse> future = httpclient.execute(httpGet, null); HttpResponse httpResponse = future.get(); System.out.println(httpResponse.getStatusLine()+"==="+httpGet.getRequestLine()); }
4:异步的post方式请求:其中可以在回调函数中加入自己的业务逻辑
public static void doPostAsyn(String url,String outStr) throws ParseException, IOException, InterruptedException, ExecutionException{ CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault(); httpAsyncClient.start(); HttpPost httpost = new HttpPost(url); // httpost.addHeader(HTTP.CONTENT_TYPE, "application/json"); StringEntity se=new StringEntity(outStr,"UTF-8"); se.setContentType("application/json"); se.setContentEncoding(new BasicHeader("Content-Type", "application/json")); httpost.setEntity(se); Future<HttpResponse> future = httpAsyncClient.execute(httpost,null); System.out.println(future.get().toString()); //String result = EntityUtils.toString(response.getEntity(),"UTF-8"); //jsonObject = JSONObject.fromObject(result); }