java swing通过httpclient向服务器端发送post请求如何做
发布网友
发布时间:2022-05-11 17:01
我来回答
共1个回答
热心网友
时间:2023-10-15 20:14
/**
* @Description: post请求远程http链接
* @param url 链接地址
* @param bean 实体对象参数
* @param params 多个字符串参数
* @return json
* @throws Exception
*/
public static String doPostWithBean(String url,Object bean,String...params) throws Exception {
System.err.println(params.length);
HttpClient client = getHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
for(Field f : bean.getClass().getDeclaredFields()){
f.setAccessible(true);
if(f.get(bean)!=null&&!"".equals(f.get(bean).toString())){
entity.addPart(f.getName(),new StringBody(f.get(bean).toString(),Charset.forName("UTF-8")));
}
}
for(Field f : bean.getClass().getSuperclass().getDeclaredFields()){
f.setAccessible(true);
if(f.get(bean)!=null&&!"".equals(f.get(bean).toString())){
entity.addPart(f.getName(),new StringBody(f.get(bean).toString(),Charset.forName("UTF-8")));
}
}
if(params!=null && params.length!=0) {
Map<String,Object> paramsMap = MapTool.getParamMap(params);
for(String paramName:paramsMap.keySet()){
entity.addPart(paramName,new StringBody((String) paramsMap.get(paramName),Charset.forName("UTF-8")));
}
}
httppost.setEntity(entity);
String resp = null;
try {
HttpResponse response = client.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resp = EntityUtils.toString(resEntity, "UTF-8");
}
if (resEntity != null) {
EntityUtils.consume(resEntity);
}
} finally {
client.getConnectionManager().shutdown();
}
return resp;
}