您当前的位置: 首页 >  Java

wu@55555

暂无认证

  • 3浏览

    0关注

    201博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java POST接口报错417

wu@55555 发布时间:2019-11-07 14:13:55 ,浏览量:3

java POST接口报错417

背景:开发语言JAVA,POST供应商HTTP接口时发现报错417,但是使用POSTMAN连接接口又可以连接上

处理步骤: 1.首先百度搜索了这种报错的原因,主要有以下原因: (1)与HTTP1.1中100-continue协议有关 (2)服务器或接口有限制 2.因为多数博客都说与100协议有关,与是开始查阅相关资料,基本都是说在请求头中添加Expect为100-Continue, httppost.setHeader(“Expect”, “100-Continue”); 于是添加后再次测试,发现还是报错417,再将该请求头设置为空,还是报错,说明报错与这个无关。 3.考虑接口限制的问题,首先去请教了公司的技术顾问,得知这类错误引发可能是 (1)一个接口被访问多次但全从一个response出去导致 (2)100-Continue协议导致 (3)也可能是实际结果不符合预期结果导致 4.向对接的供应商询问了接口是否有限制,供应商表示没有限制 5.思路到这里断了,于是换了一个httpclient的jar包另外再写了一个POST接口的方法,这次除了收到了417报错状态码,还收到了回执:报文内容为空,请检查报文内容或者编码是否有误。 6.看到这个回执,想到了他们接口好像只能接收XML格式的报文,之前在请求头设置了XML格式, httppost.setHeader(“Content-Type”, “application/xml”); 但是不是还需要再为报文内容设置一次,于是尝试了一下, StringEntity se = new StringEntity(xml, “utf-8”); se.setContentType(“application/xml”); // 设置数据类型 不加会报错 设置完后发现果然接通了,收到了回执 7.完整POST接口方法如下: import org.apache.http.client.config.RequestConfig; import org.json.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients;

/** * 发送HTTP * * @param xml 报文 * @param url 地址 * @param params 授权信息 * @return */ public static net.sf.json.JSONObject sendHttp(String xml, String url, HashMap params) { net.sf.json.JSONObject res = new net.sf.json.JSONObject(); try { HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); // httppost.setHeader(“Expect”, “100-Continue”); // httppost.setHeader(“Content-Type”, “application/xml”); for (String key : params.keySet()) { // 设置授权参数 httppost.setHeader(key, params.get(key)); } //其内容是接收方需要的参数和消息内容 StringEntity se = new StringEntity(xml, “utf-8”); se.setContentType(“application/xml”); // 设置数据类型 不加会报错417 httppost.setEntity(se); // 设置请求和传输超时时间 单位毫秒 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build(); httppost.setConfig(requestConfig); HttpResponse response = httpclient.execute(httppost); System.out.println(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result_xml = org.apache.http.util.EntityUtils.toString(response.getEntity(), “utf-8”); res.put(“state”, “success”); res.put(“message”, result_xml); } else { res.put(“state”, “fail”); res.put(“message”, “发送失败,请检查接口地址和验证信息是否正确”); } } catch (Exception e) { res.put(“state”, “fail”); res.put(“message”, “发送失败,” + e.toString()); } return res; }

参考网址: 【1】https://blog.csdn.net/weixin_30496751/article/details/99464929 【2】https://blog.csdn.net/ahzxj2012/article/details/52510491

关注
打赏
1664985904
查看更多评论
立即登录/注册

微信扫码登录

0.0439s