使用Apache HttpClient 4.x發送Json資料

來源:互聯網
上載者:User

標籤:except   obj   ddr   color   bsp   tpc   waiting   stc   不同   

Apache HttpClient是Apache提供的一個開源組件,使用HttpClient可以很方便地進行Http請求的調用。自4.1版本開始,HttpClient的API發生了較大的改變,很多方法的調用方式已經和3.x版本不同。本文使用的是當前最新的4.5.3版本。

首先在pom檔案中引入httpcomponents依賴包:

1 <dependency>2     <groupId>org.apache.httpcomponents</groupId>3     <artifactId>httpclient</artifactId>4     <version>4.5.3</version>5 </dependency>

本文展示的是POST請求。

 1 import java.io.IOException; 2  3 import org.apache.commons.lang3.ObjectUtils; 4 import org.apache.commons.lang3.StringUtils; 5 import org.apache.http.Consts; 6 import org.apache.http.HttpStatus; 7 import org.apache.http.ParseException; 8 import org.apache.http.client.config.RequestConfig; 9 import org.apache.http.client.methods.CloseableHttpResponse;10 import org.apache.http.client.methods.HttpPost;11 import org.apache.http.entity.ContentType;12 import org.apache.http.entity.StringEntity;13 import org.apache.http.impl.client.CloseableHttpClient;14 import org.apache.http.impl.client.HttpClients;15 import org.apache.http.util.EntityUtils;16 17 /**18  * @author 19  *20  * @date 2017年5月18日 上午9:17:3021  *22  * @Description23  */24 public class HttpPostUtils {25     /**26      * 27      * @param uri28      *            the request address29      * @param json30      *            the request data that must be a JSON string31      * @param connectTimeout32      *            the timeout in milliseconds until a connection is established33      * @param connectionRequestTimeout34      *            the timeout in milliseconds used when requesting a connection35      *            from the connection manager36      * @param socketTimeout37      *            the socket timeout in milliseconds, which is the timeout for38      *            waiting for data or, put differently, a maximum period39      *            inactivity between two consecutive data packets40      * @return null when method parameter is null, "", " "41      * @throws IOException42      *             if HTTP connection can not opened or closed successfully43      * @throws ParseException44      *             if response data can not be parsed successfully45      */46     public String postJson(String uri, String json, int connectTimeout, int connectionRequestTimeout, int socketTimeout)47             throws IOException, ParseException {48         if (StringUtils.isAnyBlank(uri, json)) {49             return null;50         }51 52         CloseableHttpClient client = HttpClients.createDefault();53         HttpPost post = new HttpPost(uri);54         // Create request data55         StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);56         // Set request body57         post.setEntity(entity);58 59         RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)60                 .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();61         post.setConfig(config);62         // Response content63         String responseContent = null;64         CloseableHttpResponse response = null;65         try {66             response = client.execute(post);67             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {68                 responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());69             }70         } finally {71             if (ObjectUtils.anyNotNull(response)) {72                 response.close();73             }74             if (ObjectUtils.anyNotNull(client)) {75                 client.close();76             }77         }78         return responseContent;79     }80 }

 

使用Apache HttpClient 4.x發送Json資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.