https工具类设置请求头,使用apache的httpclient实现

时间:2025-02-17 12:28:19
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • public class HttpsClientUtil {
  • private static final String CHAREST = "utf-8";
  • /**
  • * 发送post请求
  • * @param url
  • * @return
  • */
  • public static String doPost(String url,String mapParam){
  • HttpClient httpClient = null;
  • HttpPost httpPost = null;
  • String result = null;
  • try{
  • httpClient = new SSLClient();
  • httpPost = new HttpPost(url);
  • //设置参数
  • ("Content-Type", "application/json");
  • ("Authorization", "Basic YWRtaW46");
  • StringEntity s = new StringEntity(mapParam, CHAREST);
  • (new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
  • (s);
  • HttpResponse response = (httpPost);
  • if(response != null){
  • HttpEntity resEntity = ();
  • if(resEntity != null){
  • result = (resEntity,CHAREST);
  • }
  • }
  • }catch(Exception ex){
  • ();
  • }
  • return result;
  • }
  • /**
  • * 发送get请求
  • * @param url 链接地址
  • * @return
  • */
  • public static String doGet(String url){
  • HttpClient httpClient = null;
  • HttpGet httpGet= null;
  • String result = null;
  • try {
  • httpClient = new SSLClient();
  • httpGet = new HttpGet(url);
  • HttpResponse response = (httpGet);
  • if(response != null){
  • HttpEntity resEntity = ();
  • if(resEntity != null){
  • result = (resEntity,CHAREST);
  • }
  • }
  • } catch (Exception e) {
  • ();
  • }
  • return result;
  • }
  • /**
  • * 发送get请求,并设置get的请求头
  • * @param url 链接地址
  • * @return
  • */
  • public static String setHeadDoGet(String url,Map<String,String> headers){
  • HttpClient httpClient = null;
  • HttpGet httpGet= null;
  • String result = null;
  • try {
  • httpClient = new SSLClient();
  • httpGet = new HttpGet(url);
  • for (<String, String> e : ()) {
  • ((), ());
  • }
  • HttpResponse response = (httpGet);
  • if(response != null){
  • HttpEntity resEntity = ();
  • if(resEntity != null){
  • result = (resEntity,CHAREST);
  • }
  • }
  • } catch (Exception e) {
  • ();
  • }
  • return result;
  • }
  • }