JAVA HTTPPOST

Posted on   jiaoqing。  阅读(1050)  评论(0编辑  收藏  举报
public static String post(String url, Map<String, Object> paramMap) throws ClientProtocolException, IOException,Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
//设置认证信息
JSONObject json=new JSONObject(paramMap);
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build());
List<NameValuePair> formparams = setHttpParams(paramMap);
UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
//通过setEntity()设置参数给post
httpPost.setEntity(param);
//利用httpClient的execute()方法发送请求并且获取返回参数
HttpResponse response = httpClient.execute(httpPost);
String httpEntityContent = getHttpEntityContent(response);
httpPost.abort();
return httpEntityContent;
}
/**
* 设置请求参数
* @param
* @return
*/
private static List<NameValuePair> setHttpParams(Map<String, Object> paramMap) {
List<NameValuePair> formparams = new ArrayList<>();
Set<Map.Entry<String, Object>> set = paramMap.entrySet();
for (Map.Entry<String, Object> entry : set) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
return formparams;
}

/**
* 获得响应HTTP实体内容
* @param response
* @return
* @throws java.io.IOException
* @throws java.io.UnsupportedEncodingException
*/
private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
//通过HttpResponse 的getEntity()方法获取返回信息
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
br.close();
is.close();
return sb.toString();
}
return "";
}
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?

随笔 - 287, 文章 - 0, 评论 - 3, 阅读 - 42万

Copyright © 2025 jiaoqing。
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示