赞
踩
项目中遇到一个请求方式要求:
1 、POST 请求
2 、Content-Type: text/xml; charset=utf-8
项目是Java代码 使用的httpclick发送的请求,接下来让我看下如何实现,本部分只提供核心请求代码,之前分享过httpclick发送请求工具类,有兴趣的小伙伴可以查看下之前文章(●'◡'●)
代码如下:
- public static String doPost(String url, JSONObject params) {
- String result = "";
- CloseableHttpResponse response = null;
- try {
- //设置请求地址,创建 URIBuilder
- URIBuilder uriBuilder = new URIBuilder(url);
- if (!params.isEmpty()) {
- List<NameValuePair> nvp = new ArrayList<>();
- for (String key : params.keySet()) {
- nvp.add(new BasicNameValuePair(key, params.getString(key)));
- }
- uriBuilder.setParameters(nvp);
- }
- HttpPost httpPost = new HttpPost(uriBuilder.build());
- httpPost.setConfig(REQUEST_CONFIG);
- //返回json数据时不需要下面一行header
- httpPost.setHeader("Accept", "text/xml");
- //定义Content-Type
- httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
-
- //发起请求
- response = HTTP_CLIENT.execute(httpPost);
- if (response.getStatusLine().getStatusCode() == CODE) {
- HttpEntity entity = response.getEntity();
- result = EntityUtils.toString(entity, "utf-8");
- } else {
- log.error("\n请求接口错误,请检查接口是否可以正常访问!");
- }
- log.info("\n发起接口请求信息\n地址:{}\n参数:{}\n请求方式:{}\n请求结果:{}", url, params.toJSONString(), httpPost.getMethod(), result);
- } catch (URISyntaxException | IOException e) {
- log.error("\n请求接口错误,请检查接口是否可以正常访问!\n地址:{},\n参数:{}", url, params.toJSONString());
- throw new RuntimeException(e.getMessage());
- } finally {
- try {
- if (response != null) {
- response.close();
- log.info("关闭连接请求!");
- }
- } catch (IOException e) {
- log.error("关闭发送请求失败!{}", e.getMessage());
- }
- }
- return result;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。