HttpClient

package Testutill;

import java.io.;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.
;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import static Testutill.JDBC.sleep;

/**

  • @author 马弦

  • @date 2017年10月23日 下午2:49

  • HttpClient工具类
    */
    public class HttpUtil {
    private static Logger logger = Logger.getLogger( HttpUtil.class );

    /**

    • get请求

    • @return
      */
      public static String doGet(String url) {
      try {
      HttpClient client = new DefaultHttpClient();
      //发送get请求
      HttpGet request = new HttpGet( url );
      HttpResponse response = client.execute( request );

       /**请求发送成功,并得到响应**/
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
           /**读取服务器返回过来的json字符串数据**/
           String strResult = EntityUtils.toString( response.getEntity() );
      
           return strResult;
       }
      

      } catch (IOException e) {
      e.printStackTrace();
      }

      return null;
      }

    /**

    • get请求

    • @return
      */
      public static String doGet(String url,String input,String head) {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      String strResult = null;
      String repose = “”;

      // json数据拼接成get请求参数
      try {
      com.alibaba.fastjson.JSONObject json = JSON.parseObject(input);
      String utrStr = “”;
      for (Object var : json.keySet()) {
      utrStr = utrStr + var.toString() + “=” + json.get(var).toString() + “&”;
      }

       // 去掉最后一位$
       utrStr = utrStr.substring(0, utrStr.length() - 1);
       url = url + "?" + utrStr;
      
       HttpGet request = new HttpGet(url);
       RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
       request.setConfig(requestConfig);
      
       // 添加请求头
       if(!head.trim().isEmpty()){
           System.out.println("head "+head);
           Map<String,String> heads = (Map<String,String>)JSON.parse(head.trim());
           for (Map.Entry<String, String> entry : heads.entrySet()) {
               request.addHeader(entry.getKey(), entry.getValue());
           }
       }
      
       HttpResponse response = (HttpResponse) httpClient.execute(request);
       System.out.println("请求:" + url);
       /** 请求发送成功,并得到响应 **/
       if (((org.apache.http.HttpResponse) response).getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
           /** 读取服务器返回过来的json字符串数据 **/
           HttpEntity entity = ((org.apache.http.HttpResponse) response).getEntity();
           strResult = EntityUtils.toString(entity, "utf-8");
           System.out.println("响应:" + strResult);
           return strResult;
       } else {
           System.out.println("get请求提交失败:" + url);
       }
      

      } catch (IOException e) {
      System.out.println(“get请求提交失败:” + url + “异常信息:” + e);
      }
      return strResult;
      }

    /**

    • POST请求
    • @param url
    • @param request
    • @param cookies
    • @return response
    • json形式
      */
      public static CloseableHttpResponse doPost(String url,String request,String cookies) {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost2 = new HttpPost(url);
      CloseableHttpResponse response=null;
      httpPost2.addHeader(“Content-Type”, “application/json”);
      httpPost2.setHeader( “authorization”, cookies );
      try {
      httpPost2.setEntity(new StringEntity(request ));
      response = httpClient.execute(httpPost2);
      System.out.println( “值”+HttpUtil.getResponeJson( response ));
      return response;
      } catch (IOException e) {
      e.printStackTrace();
      }
      return response;
      }

    /**

    • POST请求

    • @param url

    • @param request

    • @return response

    • json形式
      */
      public static HttpResponse doPost(String url,String request) {
      logger.info(“url==” + url);
      String repose = “”;
      HttpClient client = null;
      client = HttpClients.createDefault();
      RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000000).setConnectTimeout(2000000).build();
      HttpPost post = new HttpPost(url);
      post.setConfig(requestConfig);
      HttpResponse response = null;
      if (request.contains("&")) {
      List nvps = new ArrayList();
      String[] sourceStrArray = request.split("&");

       for(int i = 0; i < sourceStrArray.length; ++i) {
           String[] temp = sourceStrArray[i].split("=");
           if (temp.length == 2) {
               nvps.add(new BasicNameValuePair(temp[0], temp[1]));
           }
       }
      
       try {
           post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
           try {
               response = client.execute(post);
           } catch (IOException e) {
               e.printStackTrace();
           }
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       }
      

      } else if (request.startsWith("{")) {
      post.addHeader(“Content-type”, “application/json; charset=utf-8”);
      new ArrayList();
      // JSONObject json = JSON.parseObject(request);
      JSONObject json = JSONObject.fromObject(request);

       StringEntity entity = new StringEntity(json.toString(), "utf-8");
       entity.setContentEncoding("UTF-8");
       entity.setContentType("application/json");
       post.setEntity(entity);
       try {
           response = client.execute(post);
       } catch (IOException e) {
           e.printStackTrace();
       }
      

      }

// repose = readResponse(response);
sleep(1000);
return response;
}

// 接口API请求,纯post请求方式
public static String postApi(String url, String content, String headerJSON) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    String response = "";

    try {
        // 配置
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
                .build();
        httpPost = new HttpPost(url);
        System.out.println("URL:"+url);
        httpPost.setConfig(requestConfig);

        // 请求内容
        if (content.startsWith("{") && content.endsWith("}")) {
            com.alibaba.fastjson.JSONObject json = JSON.parseObject(content);
            StringEntity entity = new StringEntity(json.toString(), "utf-8");// 解决中文乱码问题
            httpPost.setEntity(entity);
            System.out.println("请求:"+content);
        } else {
            throw new RuntimeException("请检查请求内容是否填写正确");
        }

        // 请求头
        com.alibaba.fastjson.JSONObject header = (com.alibaba.fastjson.JSONObject) JSON.parse(headerJSON);
        for (Object var : header.keySet()) {
            httpPost.addHeader(var.toString(), header.get(var).toString());
        }
        System.out.println("请求头:"+headerJSON);

        // 发送
        CloseableHttpResponse res = httpClient.execute(httpPost);
        int statusCode = res.getStatusLine().getStatusCode();

        // 响应
        if (HttpStatus.SC_OK != statusCode) {
            System.err.println("response状态码 ==" + statusCode);
        }
        response = EntityUtils.toString(res.getEntity(), "utf-8");

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new RuntimeException("请求端口有误");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new RuntimeException("请求地址有误");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("响应有误,请检查");
    } finally {
        if(httpClient != null){
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("响应:"+response);
    return response;
}


/**
 * POST请求
 * @param  url
 * @param map
 * @return response
 * x-www-form-urlencoded形式
 */
public static String doPost_Cookie(String url,Map<String, String> map, String charset) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        CookieStore cookieStore = new BasicCookieStore();
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
            httpPost.setEntity(entity);
        }
        HttpResponse response=httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("result : "+result);
        String JSESSIONID = null;
        String cookie_user = null;
        List<Cookie> cookies = cookieStore.getCookies();
        System.out.println( "cookies : "+cookies );
        for (int i = 0; i < cookies.size(); i++) {

// System.out.println( "cookies.get(i).getName() : "+cookies.get(i).getName() );
// System.out.println( "cookies.get(i).getValue() : "+cookies.get(i).getValue() );
if (cookies.get(i).getName().equals(“JSESSIONID”)) {
JSESSIONID = cookies.get(i).getValue();
}
if (cookies.get(i).getName().equals(“cookie_user”)) {
cookie_user = cookies.get(i).getValue();
}
}
// if (cookie_user != null) {
// result = JSESSIONID;
// }
result = JSESSIONID;
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}

/**
 * POST请求
 * @param  url
 * @param map
 * @return response
 * x-www-form-urlencoded形式
 */
public static Cookie doPost_Cookie1(String url,Map<String, String> map, String charset) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    Cookie cookies = null;
    try {
        CookieStore cookieStore = new BasicCookieStore();
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
            httpPost.setEntity(entity);
        }
        HttpResponse response=httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("result : "+result);
        cookies= (Cookie) cookieStore.getCookies();
        System.out.println( "cookies : "+cookies );

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return cookies;
}

/**
 * POST请求
 * @param  url
 * @param map
 * @return response
 * x-www-form-urlencoded形式
 */
public static String doPost(Cookie cookie,String url,Map<String, String> map, String charset) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        CookieStore cookieStore = new BasicCookieStore();
        httpPost.setHeader("Cookies",cookie.toString());
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
            httpPost.setEntity(entity);
        }
        HttpResponse response=httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("result : "+result);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}


/**
 * POST请求
 * @param  url
 * @param map
 * @return response
 * x-www-form-urlencoded形式
 */
public static String doPost(String url,Map<String, String> map, String charset, String sessionId) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        CookieStore cookieStore = new BasicCookieStore();
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        if(null != sessionId){
            httpPost.setHeader("Cookie", "[[version: 0][name: JSESSIONID][value: "+sessionId+"][domain: 10.166.15.190][path: /credit-portal/][expiry: null]]");
            System.out.println( httpPost.getAllHeaders() );
        }
        httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
            httpPost.setEntity(entity);
        }
        HttpResponse response=httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("result : "+result);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}


/**
 * 设置CookieStore(用于请求json格式的参数)
 * @param url
 * @param request
 * @return cookiestore
 */
public static HttpResponse doPost1(String url,String request,String cookiestore) {
    logger.info("url==" + url);
    String repose = "";
    HttpClient client = null;
    client = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
    HttpPost post = new HttpPost(url);
    post.setConfig(requestConfig);
    post.setHeader("authorization", cookiestore);
    HttpResponse response = null;
    if (request.contains("&")) {
        List<NameValuePair> nvps = new ArrayList();
        String[] sourceStrArray = request.split("&");

        for(int i = 0; i < sourceStrArray.length; ++i) {
            String[] temp = sourceStrArray[i].split("=");
            if (temp.length == 2) {
                nvps.add(new BasicNameValuePair(temp[0], temp[1]));
            }
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            try {
                response = client.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else if (request.startsWith("{")) {
        post.addHeader("Content-type", "application/json; charset=utf-8");
        new ArrayList();

// JSONObject json = JSON.parseObject(request);
JSONObject json = JSONObject.fromObject(request);
StringEntity entity = new StringEntity(json.toString(), “utf-8”);
entity.setContentEncoding(“UTF-8”);
entity.setContentType(“application/json”);
post.setEntity(entity);
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
}

// repose = readResponse(response);
sleep(1000);
return response;
}

/**
 * CookieStore得到Cookie值
 * @param username
 * @return
 */
public static  String getCookie(String ip,String username,String password) {
    String url = "http://" + ip + "/authority-app/loginService/login.htm";
    String request = "{\"queryTable\":{\"scubeHeader\":{\"transCode\":\"loginService/login\",\"errorCode\":\"\",\"errorMsg\":\"\"},\"scubeBody\":{\"contextData\":{\"domainVilidate\":\"\",\"data\":{\"userInfo\":{\"tlrNo\":\"" + username + "\",\"password\":\"" + password + "\",\"brManagerNo\":\"\"}}}}}}";
    HttpResponse HttpResponse = HttpUtil.doPost( url, request );
    String result = HttpUtil.getResponeJson( HttpResponse ).replace( "\\","" );
    System.out.println( "返回的result为: " + result );
    String str="id\":.*loginInfoKey";
    String cookie=null;
    Pattern pattern = Pattern.compile(str);
    Matcher matcher=pattern.matcher( result );
    System.out.println(matcher.matches());
    while(matcher.find()){
        cookie=matcher.group().replace( "id\":","" ).replace( ",\"loginInfoKey","" ).replace( "\"" ,"").trim();
        System.out.println("*****登陆成功后返回的cookie为: "+cookie);
    }
    return cookie;
}


/**
 * CookieStore得到Cookie值
 * @param url
 * @return
 */
public static  String getCookie(String url,String request) {

// String url = “http://” + ip + “/authority-app/loginService/login.htm”;
// String request = “{“queryTable”:{“scubeHeader”:{“transCode”:“loginService/login”,“errorCode”:”",“errorMsg”:""},“scubeBody”:{“contextData”:{“domainVilidate”:"",“data”:{“userInfo”:{“tlrNo”:"" + username + “”,“password”:"" + password + “”,“brManagerNo”:""}}}}}}";
HttpResponse HttpResponse = HttpUtil.doPost( url, request );
String result = HttpUtil.getResponeJson( HttpResponse ).replace( “\”,"" );
System.out.println( “返回的result为: " + result );
String str=“id”:.*loginInfoKey”;
String cookie=null;
Pattern pattern = Pattern.compile(str);
Matcher matcher=pattern.matcher( result );
System.out.println(matcher.matches());
while(matcher.find()){
cookie=matcher.group().replace( “id”:","" ).replace( “,“loginInfoKey”,”" ).replace( “”" ,"").trim();
System.out.println("*****登陆成功后返回的cookie为: "+cookie);
}
return cookie;
}

/**
 * 返回json(用于请求json格式的参数)
 * @param response
 * @return
 */
public static String getResponeJson (HttpResponse response){
    String jsonString = null;
    StatusLine status = response.getStatusLine();
    int state = status.getStatusCode();
    System.out.println( "state 为: "+state );
    if (state == HttpStatus.SC_OK) {
        HttpEntity responseEntity = response.getEntity();
        System.out.println( "responseEntity 为: "+responseEntity );
        try {
            jsonString = EntityUtils.toString( responseEntity );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return jsonString;
}


/**
 * 读取配置Url
 * @param key
 * @return
 */
public static String getPropertiesUrlValue (String path,String key,String value){
    String key1 = null;
    String value1 = null;
    File file = new File("src/main/resources/"+path);
    InputStreamReader encoding = null;
    try {
        InputStream in = new FileInputStream(file);
        encoding = new InputStreamReader(in, "utf-8");// properties文件编码转UTF-8
        Properties properties = new Properties();
        properties.load(encoding);
        key1 = properties.getProperty(key);
        value1 = properties.getProperty(value);
        return key1.trim()+":"+value1.trim();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (encoding != null) {
            try {
                encoding.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

/**
 * 读取配置Db
 * @param key
 * @return
 */
public static String getPropertiesDbValue (String path,String key){
    String key1 = null;
    File file = new File("src/main/resources/"+path);
    InputStreamReader encoding = null;
    try {
        InputStream in = new FileInputStream(file);
        encoding = new InputStreamReader(in, "utf-8");// properties文件编码转UTF-8
        Properties properties = new Properties();
        properties.load(encoding);
        key1 = properties.getProperty(key);
        return key1.trim();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (encoding != null) {
            try {
                encoding.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

/**
 * 写入配置文件
 * @param key1
 * @return
 */

public static void setProperties(String key1) throws IOException {
    Properties pro = new Properties();

    pro.setProperty( "申请编号", key1 );

// pro.setProperty( “合同编号”, key2 );
pro.store( new FileOutputStream( “data.properties” ), “data配置” );

}

/**
 * @param url
 * @param request
 * @return
 * 白条申请专用post
 */
public static HttpResponse doPost_blankLimitApply(String url,String request) {
    logger.info("url==" + url);
    String repose = "";
    HttpClient client = null;
    client = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).build();
    HttpPost post = new HttpPost(url);
    post.setConfig(requestConfig);
    HttpResponse response = null;
    post.addHeader("Content-type", "application/json; charset=utf-8");
    new ArrayList();

// JSONObject json = JSON.parseObject(request);
JSONObject json = JSONObject.fromObject(request);
StringEntity entity = new StringEntity(json.toString(), “utf-8”);
entity.setContentEncoding(“UTF-8”);
entity.setContentType(“application/json”);
post.setEntity(entity);
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}

// repose = readResponse(response);
return response;
}

public static String requestService(String reqUrl,String json)  {
   try {
	   String r = URLEncoder.encode(json, "UTF-8");
       reqUrl += r;
	} catch (Exception e) {
		e.printStackTrace();
	}
    System.out.println("请求参数:" + reqUrl);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    HttpGet httpGet = new HttpGet(reqUrl);
    System.out.println("executing request" + httpGet.getRequestLine());
    try {
        client = HttpClients.createDefault();
        response = client.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == 200) {

            String result = EntityUtils.toString(response.getEntity());

            System.out.println("executing result---连接正常" + result);
            return result;
        } else {
            System.out.println("executing result---服务器连接异常");
        }


    } catch (Exception e) {
        System.out.println("Exception================" + e.toString());
    } finally {
    	try {
    		if (response != null) {
    			response.close();
    		}
    		if (client != null) {
    			client.close();
    		}

		} catch (Exception e2) {
		}
    }
    return  null;
}


public static void main(String args[]){
    String ip="10.166.8.58:18082";

// getCookie(ip,“88888888”,“88888888”);

// System.out.println(“getPropertiesValue :-------” + getPropertiesUrlValue( “” ,"")//“config/common/url.properties”,“地址58”
System.out.println( “”+getPropertiesUrlValue( “config/common/url.properties”,“服务器ip” ,“服务器端口”) );
// System.out.println(“getPropertiesValue :-------”);
//
// try {
// setProperties(“ddddd3333d”);
// System.out.println(“getProperti222222esValue :-------”);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}

/**
 * 产生随机数
 * @param i
 * @return k
 */
public static int getRandom(int i){
    int k= new Random().nextInt(i)+1;
    System.out.println( "生成的随机数k为:"+k );
    return k;
}





public static String httpPostWithJSON(String url){

    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();
    String respContent = null;

// json方式
JSONObject jsonParam = new JSONObject();
jsonParam.put(“name”, “admin”);
jsonParam.put(“pass”, “123456”);
StringEntity entity = new StringEntity(jsonParam.toString(),“utf-8”);//解决中文乱码问题
entity.setContentEncoding(“UTF-8”);
entity.setContentType(“application/json”);
httpPost.setEntity(entity);
System.out.println();

表单方式
// List pairList = new ArrayList();
// pairList.add(new BasicNameValuePair(“applyToken”, “a70948d569594f8c8cab16b242639f0b”));
// pairList.add(new BasicNameValuePair(“companyName”, “测试融贯限公司phil”));
try {
// httpPost.setEntity(new UrlEncodedFormEntity(pairList, “utf-8”));
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he,“UTF-8”);
}
}catch (Exception e){
System.out.println(e.getMessage());
}
return respContent;
}

public static String httpPostWithData(String url,Map<String,Object> map){
    String respContent = null;

json方式
// JSONObject jsonParam = new JSONObject();
// jsonParam.put(“name”, “admin”);
// jsonParam.put(“pass”, “123456”);
// StringEntity entity = new StringEntity(jsonParam.toString(),“utf-8”);//解决中文乱码问题
// entity.setContentEncoding(“UTF-8”);
// entity.setContentType(“application/json”);
// httpPost.setEntity(entity);
// System.out.println();

    try {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //        表单方式
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            pairList.add(new BasicNameValuePair(entry.getKey(),  entry.getValue().toString()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he,"UTF-8");
        }
    }catch (Exception e){
        System.err.println("e.getMessage() :  "+e.getMessage());
    }
    return respContent;
}


public static String resultMatcher(String str,String regEx){
    // 正则表达式规则String regEx
    // 编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小写的写法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 查找字符串中是否有匹配正则表达式的字符/字符串
    boolean rs = matcher.find();
    System.out.println("rs :" +rs);
    if(rs){
        System.out.println("匹配出来的内容为 :" +matcher.group());
        return matcher.group();
    }else {
        return null;
    }
}



public static String postFileMultiPart(String url,Map<String,Object> params){
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        // 创建httpget.
        HttpPost httppost = new HttpPost(url);

        //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
        httppost.setConfig(defaultRequestConfig);

        System.out.println("executing request " + httppost.getURI());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

// Map <String, ContentBody> reqParam = new HashMap <>();
// reqParam.put(“file”, new FileBody(new File(localFileName)));
// reqParam.put(“randomCode”, new StringBody(“1558588405421-78”));
// reqParam.put(“imageType”, new StringBody(“12”));
// reqParam.put(“applyToken”, new StringBody(applyToken));

        Map<String,ContentBody> reqParam=new HashMap <>(  );
        for(Map.Entry<String,Object> param1 : params.entrySet()){
            if(param1.getKey().equals( "file" )){
                reqParam.put("file", new FileBody(new File(param1.getValue().toString())));
            }else {
                reqParam.put(param1.getKey(), new StringBody(param1.getValue().toString()));
            }
        }

        for(Map.Entry<String,ContentBody> param : reqParam.entrySet()){
            multipartEntityBuilder.addPart(param.getKey(), param.getValue() );
        }
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httppost.setEntity(reqEntity);

        // 执行post请求.
        CloseableHttpResponse response = httpclient.execute(httppost);

        System.out.println("got response");

        try {
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            //System.out.println("--------------------------------------");
            // 打印响应状态
            //System.out.println(response.getStatusLine());
            if (entity != null) {
                return EntityUtils.toString(entity,Charset.forName("UTF-8"));
            }
            //System.out.println("------------------------------------");
        } finally {
            response.close();

        }
    } catch (Exception e){
        System.out.println(e.getMessage());
    }finally {
        // 关闭连接,释放资源
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值