分割url获取所有参数

场景

客户传过来一个链接,需要我们去访问,但是,这个链接中有特殊字符和中文,直接使用的话服务方收到参数乱码,所以我这里收到客户的链接之后,把参数全部取出来进行encode,然后去调用新的链接。

代码

package com.pan;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class HttpGetUtils {
    private static Logger logger = Logger.getLogger(HttpGetUtils.class);
    private static PoolingHttpClientConnectionManager cm;
    private static String EMPTY_STR = "";
    private static String UTF_8 = "UTF-8";

    public static void main(String[] args) {
        String url = "http://127.0.0.1:9999/test/interface";
        String url2 = "http://127.0.0.1:9999/test/interface?";
        String url3 = "http://127.0.0.1:9999/test/interface?ywid=";
        String url4 = "http://127.0.0.1:9999/test/interface?ywid=123";
        String url5 = "http://127.0.0.1:9999/test/interface?ywid=123&";
        String url6 = "http://127.0.0.1:9999/test/interface?ywid=123&ywcjlx=";
        String url7 = "http://127.0.0.1:9999/test/interface?ywid=123&ywcjlx==";
        String url8 = "http://127.0.0.1:9999/test/interface?ywid=123&ywcjlx=ZJTZ001&content=您好我是您的交通银行客服代表小交请问是张三先生本人吗";
        String url9 = "http://127.0.0.1:9999/test/interface?ywid=123&ywcjlx=ZJTZ001&name=张三&content=您好=我是您的交通银行客服代表小交请问是张三先生本人吗";
        String url10 = "http://127.0.0.1:9999/test/interface?value={\"aaa\":\"中文\",\"bbb\":\"终止\"}";
        try {
//            System.out.println(HttpGetUtils.doGet(url));
//            System.out.println(HttpGetUtils.doGet(url2));
//            System.out.println(HttpGetUtils.doGet(url3));
//            System.out.println(HttpGetUtils.doGet(url4));
//            System.out.println(HttpGetUtils.doGet(url5));
//            System.out.println(HttpGetUtils.doGet(url6));
//            System.out.println(HttpGetUtils.doGet(url7));
//            System.out.println(HttpGetUtils.doGet(url8));
            System.out.println(HttpGetUtils.doGet(url9));
//            System.out.println(HttpGetUtils.doGet(url10));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void init() {
        if (cm != null)
            return;
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(50);
        cm.setDefaultMaxPerRoute(5);
    }

    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String doGet(String url) throws Exception {
        return doGet(url, UTF_8);
    }

    public static String doGet(String url, String encode) throws Exception {
        StringBuffer newUrl = new StringBuffer();
        url = url.trim();
        if (url.contains("?")) {
            String[] urlArr = url.split("[?]");
            String baseUrl = urlArr[0];
            String paramStr = "";
            StringBuffer newParamStr = new StringBuffer();
            paramStr = url.substring(baseUrl.length() + 1);
            String[] paramArr = paramStr.split("[&]");
            for (int i = 0; i < paramArr.length; i++) {
                String temp = paramArr[i];
                if (null == temp || "".equals(temp.trim())) {
                    continue;
                }
                if (temp.contains("=")) {
                    String[] keyValue = temp.split("[=]");
                    newParamStr.append("&").append(keyValue[0]).append("=").append(encode(temp.substring(keyValue[0].length() + 1), encode));
                } else {
                    newParamStr.append("&").append(temp);
                }
            }
            if (newParamStr.length() > 0) {
                newUrl.append(baseUrl).append("?").append(newParamStr.deleteCharAt(0));
            } else {
                newUrl.append(baseUrl);
            }
        } else {
            newUrl.append(url);
        }
//        System.out.println("encode之前=" + url);
        logger.info("url encode之后=" + newUrl.toString());
        HttpGet httpGet = new HttpGet(newUrl.toString());
        return getResult(httpGet);
    }

    private static String encode(String str, String encode) throws Exception {
        if (null == str || "".equals(str.trim())) {
            return "";
        }
        try {
            return URLEncoder.encode(str, encode);
        } catch (UnsupportedEncodingException e) {
            logger.error("encode", e);
            throw e;
        }
    }

    private static String getResult(HttpRequestBase request) {
        CloseableHttpClient httpClient = getHttpClient();
        try {
            logger.debug("httpClient execute start!");
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                logger.debug("result is: " + result);
                response.close();
                logger.debug("response has closed !");
                return result;
            }
            logger.debug("response's entity is null!");
        } catch (ClientProtocolException e) {
            logger.error("getResult error:", e);
        } catch (IOException e) {
            logger.error("getResult error:", e);
        }
        logger.debug("response's entity is null,return empty string!");
        return EMPTY_STR;
    }
}

jar

lib/httpclient-4.5.jar
lib/httpcore-4.4.1.jar
lib/log4j-1.2.17.jar

你可能感兴趣的:(Java)