Java 使用 httpClient 发送get、post请求

maven 依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>
get 请求

带参数的 get 请求

public static void getXijingTemplate() throws Exception {
    String url = "http://www.example.com";
    URIBuilder builder = new URIBuilder(url);
    builder.addParameter("username", "username");
    builder.addParameter("password", "123456");
    URI uri = builder.build();
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpGet);
    System.out.println(decodeUnicode(EntityUtils.toString(response.getEntity(), Consts.UTF_8)));
}
post 请求

带参数的 post 请求

public static void executeGet() throws IOException {
    String url = "http://www.example.com";
    JSONObject param = JSONObject.parseObject(params);
    StringEntity entity = new StringEntity(param.toJSONString(), Charset.forName("UTF-8"));
    HttpPost post = new HttpPost(url);
    // 构造消息头
    post.setHeader("Content-type", "application/json; charset=utf-8");
    entity.setContentEncoding("UTF-8");
    // 发送Json格式的数据请求
    entity.setContentType("application/json");
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    System.out.println(decodeUnicode(EntityUtils.toString(response.getEntity(), Consts.UTF_8)));
}

有的请求返回的结果字符是 unicode 类型的,对于中文,不便于排查问题,可以使用以下的方法处理返回的结果

//Unicode转中文
public static String decodeUnicode(final String unicode) {
    StringBuffer string = new StringBuffer();

    String[] hex = unicode.split("\\\\u");

    for (int i = 0; i < hex.length; i++) {

        try {
            // 汉字范围 \u4e00-\u9fa5 (中文)
            if(hex[i].length()>=4){//取前四个,判断是否是汉字
                String chinese = hex[i].substring(0, 4);
                try {
                    int chr = Integer.parseInt(chinese, 16);
                    boolean isChinese = isChinese((char) chr);
                    //转化成功,判断是否在  汉字范围内
                    if (isChinese){//在汉字范围内
                        // 追加成string
                        string.append((char) chr);
                        //并且追加  后面的字符
                        String behindString = hex[i].substring(4);
                        string.append(behindString);
                    }else {
                        string.append(hex[i]);
                    }
                } catch (NumberFormatException e1) {
                    string.append(hex[i]);
                }

            }else{
                string.append(hex[i]);
            }
        } catch (NumberFormatException e) {
            string.append(hex[i]);
        }
    }

    return string.toString();
}


/**
 * 判断是否为中文字符
 *
 * @param c
 * @return
 */
public static boolean isChinese(char c) {
    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
            || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
            || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
            || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
            || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
            || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
        return true;
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值