java post rest json_以JSON对象作为有效载荷的REST API的POST请求

小编典典

在跟踪了许多帖子和教程超过24小时后,我知道我没有正确发送URL参数。而且我还了解到使用 ApacheHttpClient进行 REST

API调用相对容易一些。我解决了我的HTTP错误代码400,并从服务器获取了响应。这是我的问题的工作代码。

try {

httpClient = HttpClients.createDefault();

httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");

List headers = new ArrayList(); //ArrayList to store header parameters

List urlParameters = new ArrayList(); //ArrayList to store URL parameters

urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme@totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));

headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme@totango.com"));

headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));

headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));

httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));

for (NameValuePair h : headers)

{

httpPost.addHeader(h.getName(), h.getValue());

}

response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() != 200) {

throw new RuntimeException("Failed : HTTP error code : "

+ response.getStatusLine().getStatusCode());

}

BufferedReader br = new BufferedReader(new InputStreamReader(

(response.getEntity().getContent())));

String output;

System.out.println("Output from Server .... \n");

while ((output = br.readLine()) != null) {

System.out.println(output);

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try{

response.close();

httpClient.close();

}catch(Exception ex) {

ex.printStackTrace();

}

}

2020-11-23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值