今天遇到一个比较基础,又没遇到过的问题。
这是使用httpClient调用接口的时候报的错误,错误就是http的请求头不正确。但是调用接口的是共用方法,以前都是正常用的,怎么这次就不行了呢?换了一个请求方法就好了。
话不多说,直接看解决方案。两个post请求的方法,总有一个是适合你的。根据自己项目的选择的httpClient版本进行选择不同的方法。
方法一:
public static String doPostJson(String url, String json,String token_header) throws Exception { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 httpPost.setHeader("HTTP Method","POST"); httpPost.setHeader("Connection","Keep-Alive"); httpPost.setHeader("Content-Type","application/json;charset=utf-8"); httpPost.setHeader("x-authentication-token",token_header); StringEntity entity = new StringEntity(json); entity.setContentType("application/json;charset=utf-8"); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { throw e; } finally { try { if(response!=null){ response.close(); } } catch (IOException e) { e.printStackTrace(); } } return resultString; }
方法二:
public static String doPostForBooking(String urles, String json) throws Exception { HttpURLConnection connection = null; BufferedReader br = null; InputStream inputStream = null; // 存放数据 StringBuffer sbf = new StringBuffer(); try { // 创建远程url连接对象 URL url = new URL(urles); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 允许写出 connection.setDoOutput(true); // 允许读入 connection.setDoInput(true); // 不使用缓存 connection.setUseCaches(false); // 设置参数类型是json格式 connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); connection.connect(); String body = json; BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); writer.write(body); writer.close(); // 通过connection连接,获取输入流 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); // 将输入流转换为字符串 // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } } } catch (Exception e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (Exception e2) { e2.printStackTrace(); } } if (null != inputStream) { try { inputStream.close(); } catch (Exception e2) { e2.printStackTrace(); } } // 关闭远程连接 connection.disconnect(); } return sbf.toString().replaceAll("(\r\n|\n)", ""); }