package com.ztesoft.crm.assets.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author dcy
* @Time 9/30
* @desc 用于发送http请求
*/
public class HttpClientUtil {
/**
* post请求-json参数
*/
public static String postHttp(String url, JSONObject jsonParm) {
return postHttp(url, new StringEntity(jsonParm.toString(),"UTF-8"));
}
/**
* post请求-参数
*/
public static String postHttp(String url, Map<String, String> param) throws UnsupportedEncodingException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(param != null){
Set<String> keySet = param.keySet();
for (String key : keySet) {
params.add(new BasicNameValuePair(key, param.get(key)));
}
}
return postHttp(url, new UrlEncodedFormEntity(params, "UTF-8"));
}
/**
* post请求
*/
private static String postHttp(String url, HttpEntity formEntity) {
CloseableHttpClient client = null;
HttpPost post = null;
String result = "";
try {
client = HttpClients.createDefault();
//HttpClient httpClient = new DefaultHttpClient();
post = new HttpPost(url);
post.setHeader("X-APP-ID", "8337d27b9b1ff0abb080e72cc971c096");
post.setHeader("X-APP-KEY","84580105b47abb627ab873f67c75c7f7");
List<NameValuePair> params = new ArrayList<NameValuePair>();
post.setEntity(formEntity);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接,释放资源
//httpClient.getConnectionManager().shutdown();httpClient = null;
if (post != null) {
post.releaseConnection();
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
httpClient发送请求
最新推荐文章于 2023-11-27 11:48:59 发布