restTemplate中put没有返回值,采用HTTPClient解决

    好久没写博客了,最近做项目用到了http接口取值问题。瞬间就想到了用restTemplate去实现,但是中间有一个接口需要拿到put的返回值,但是restTemplate中的put默认无返回值。我的http请求体为body,格式为json类型。

返回值都是void,于是到论坛里找解决方法,大部分给的方式就是restTemplate中的exchange,个人觉得实现比较麻烦。整了半天参数类型总是不对,后来退而求其次,还是采用更底层些的HTTPClient实现。

   public static String doPut( String url, String jsonObj){
        String resStr = null;
        HttpClient httpClient = new HttpClient();
        PutMethod putMethod = new PutMethod(url);
        putMethod.addRequestHeader( "Content-Type","application/json" );
        putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8" );
        putMethod.setRequestBody( jsonObj );
        try{
            int statusCode = httpClient.executeMethod( putMethod );
 
            if(statusCode != HttpStatus.SC_OK){
                System.out.println("Method failed: "+putMethod.getStatusLine());
                return null;
            }
       /*     byte[] responseBody = putMethod.getResponseBody();
            resStr = new String(responseBody,"UTF-8");*/

            BufferedReader reader = new BufferedReader(new InputStreamReader(putMethod.getResponseBodyAsStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while((str = reader.readLine())!=null){
                stringBuffer.append(str);
            }

            resStr = stringBuffer.toString();
            System.out.println(stringBuffer.toString());
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            putMethod.releaseConnection();
        }
        return resStr;
    }

我想要的返回结果为String类型,可以根据自己的需求做修改。

另外在网上找到了一个http工具类,可直接用。地址没有收藏,所以就直接引用了,如有侵权请联系本人,谢谢

public class HttpUtil {

    public static String postWithJsonAndParameter(String url, String json, Map param) throws Exception {
        log.info("POST: {}, Body: {}, 参数: {}", url, json, JacksonUtil.toJson(param));

        URIBuilder builder = new URIBuilder(url);
        builder.addParameters(buildParameter(param));
        HttpPost httpPost = new HttpPost(builder.build());

        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        return askFor(httpPost);
    }

    public static String postWithJson(String url, String json) throws Exception {
        log.info("POST: {}, 参数: {}", url, json);

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return askFor(httpPost);
    }

    /**
     * GET 请求
     *
     * @param url
     * @param param
     * @return
     * @throws Exception
     */
    public static String getForString(String url, Map param) throws Exception {
        log.info("GET: {}, 参数: {}", url, JacksonUtil.toJson(param));

        HttpGet httpGet;
        if (MapUtils.isEmpty(param)) {
            httpGet = new HttpGet(url);
        } else {
            URIBuilder builder = new URIBuilder(url);
            builder.addParameters(buildParameter(param));

            httpGet = new HttpGet(builder.build());
        }

        return askFor(httpGet);
    }

    /**
     * POST 请求
     *
     * @param url
     * @param param
     * @return
     * @throws Exception
     */
    public static String postForString(String url, Map param) throws Exception {
        log.info("POST: {}, 参数: {}", url, JacksonUtil.toJson(param));

        HttpPost httpPost = new HttpPost(url);
        if (MapUtils.isNotEmpty(param)) {
            httpPost.setEntity(new UrlEncodedFormEntity(buildParameter(param), "UTF-8"));
        }

        return askFor(httpPost);
    }

    private static String askFor(HttpRequestBase httpRequest) throws Exception {
        RequestConfig config = RequestConfig.custom()
                // 连接时间
                .setConnectTimeout(10 * 1000)
                // 请求超时
                .setConnectionRequestTimeout(30 * 1000)
                // 数据传输时间
                .setSocketTimeout(20 * 1000).build();

        HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpResponse response = client.execute(httpRequest);
        HttpEntity entity = response.getEntity();

        return EntityUtils.toString(entity, "UTF-8");
    }

    private static List<NameValuePair> buildParameter(Map param) {
        List<NameValuePair> nameValuePairs = new ArrayList();
        for (Iterator iterator = param.keySet().iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            String value = String.valueOf(param.get(key));

            nameValuePairs.add(new BasicNameValuePair(key, value));
        }

        return nameValuePairs;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值