common-httpclient 冷不防 2022-06-04 08:27 119阅读 0赞 Post请求: import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; // http请求 public static Result Post(String path, Map<String, String> param){ String url = "http://127.0.0.1:9191" + path; HttpClient httpClient = new HttpClient(); httpClient.getParams().setContentCharset("UTF-8"); PostMethod postMethod = new PostMethod(url); Map<String, String> headerMap = new HashMap<>(); headerMap.put("Host", "****"); headerMap.put("Accept-Encoding", "gzip"); headerMap.put("charset", "utf-8"); for (Map.Entry<String, String> entry : headerMap.entrySet()) { postMethod.addRequestHeader(entry.getKey(), entry.getValue()); } List<NameValuePair> pList = new ArrayList<>(); for(Map.Entry<String, String> entry: param.entrySet()){ pList.add(new NameValuePair(entry.getKey(), entry.getValue())); } NameValuePair[] parts = new NameValuePair[pList.size()]; for(int i = 0; i < pList.size(); i++){ parts[i] = pList.get(i); } // MultipartRequestEntity entity = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestBody(parts); try{ int result = httpClient.executeMethod(postMethod); if (result == 200) { /** 发送成功,并获取返回字符串 */ ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = postMethod.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr);//为输入流添加缓冲 String content = ""; String info = ""; while ((info = br.readLine()) != null) { content = content + info; } postMethod.releaseConnection(); Result res = new Gson().fromJson(content, Result.class); return res; } else { String msg = "请求数说读者的GO服务失败, url: " + url + ",resCode: " +result; LogDefine.LOG.error(msg); return new Result<String>(null, false, msg, null); } }catch (Exception e){ String msg = "请求数说读者的GO服务失败, url: " + url; LogDefine.LOG.error(msg, e); return new Result<String>(null, false, msg, null); } }
还没有评论,来说两句吧...