http请求的几种方式

一、

pom.xml文件里面加入:commons-httpclient.jar

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
/**
 * post 请求
 *
 * @param url
 * @param paramsMap
 * @return
 */
public static String doPostJson(String url, Map<String, Object> paramsMap,String accessToken) {
    String rep = "";
    try {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        if(StringUtils.isNotEmpty(accessToken)){
            method.setRequestHeader("Authorization", "Bearer " +accessToken);
        }
        HttpMethodParams params = method.getParams();
        params.setContentCharset("utf-8");

        RequestEntity entity = new StringRequestEntity(JSON.toJSONString(paramsMap), "application/json", "UTF-8");
        method.setRequestEntity(entity);
        //设置连接超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        //读取超时时间
        client.getHttpConnectionManager().getParams().setSoTimeout(10000);
        //设置POST方法请求超时
        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        int status = client.executeMethod(method);
        if (status == 200) {
            rep = method.getResponseBodyAsString();
        }
        method.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        log.error("error", e);
    }
    return rep;
}

二、

pom.xml文件里面加入:org.nutz.jar

<dependency>
    <groupId>org.nutz</groupId>
    <artifactId>nutz</artifactId>
    <version>${nutz.version}</version>
</dependency>
/**
 * 查询快递信息
 *
 * @param com 快递公司代码
 * @param nu  快递单号
 * @param key
 * @return 返回json字符串
 */
public static String getExpressInfo(String com, String nu, String key) {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("http://api.kuaidi100.com/api?id=").append(key);
        sb.append("&com=").append(com);
        sb.append("&nu=").append(nu);
        sb.append("&show=0&muti=1&order=desc");
        Request req = Request.create(sb.toString(), Request.METHOD.GET);
        Response resp = Sender.create(req).send();
        if (resp.isOK()) {
            return resp.getContent();
        }
    } catch (Exception e) {
        log.error("快递查询错误:" + e.getMessage());
    }
    return "";
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值