用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形式

扫描二维码关注公众号,回复: 880739 查看本文章

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);

猜你喜欢

转载自blog.csdn.net/hhs57/article/details/79625257