用httpclient調用restful接口

    IVR流程中需要調用智能語音應答,需要調用restful接口,應爲以前用spring寫過restful的接口,也用httpclient調用過自己寫的接口,就沒在意,然後各種error o(╥﹏╥)o!!

首先當然是下載httpclient的相關包和json的相關包,如下:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>

</dependency>

用了4.3.1的版本,現在已經可以使用4.5.x的版本了

首先因爲客戶端需要的parameter是json格式的字符串,需要引用一下阿里的fastjson(爲了簡單點,不用自己拼)

JSONObject jsonObj = new JSONObject();
jsonObj.put("question", "A股交易費用的構成");
jsonObj.put("userId", "admin1");

jsonObj.put("platform", "mr");

建立post object,把url添加上

HttpPost httpPost = new HttpPost(POST_URL);

然後轉換成String形式

StringEntity entity = new StringEntity(jsonObj.toString(),"UTF-8");

這裏一開始沒有添加標紅的部分,所以傳過去的參數server端不識別

添加http的消息頭

httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");  

httpPost.setEntity(entity);

HttpClient client = HttpClients.createDefault();

HttpResponse httpResponse = client.execute(httpPost);

String respContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

上邊的兩段代碼一開始只寫了第一段,想通過debug的形式找到content的值,但是可能隱藏的太深,沒找到,就只以爲服務端給返回的是200 ok,找了半天服務端的工程師,對方用restful的工具測試了,證明沒有問題,自己也用soapUI測試了一次,發現返回結果正常,這就讓我困惑了,後來從網上找到了EntityUtils工具類才發現可以把Entity轉過來。

System.out.println(respContent);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章