在很多場景下都需要用到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); }