Java Put请求工具类PutUtil

PutUtil

import java.util.Map;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

/**
 * PUT请求工具类
 */
public class PutUtil {
    public static final String UTF8 = "utf-8";
    private static final String CONTENT_TYPE = "application/json";

    public static String send(String url, Map<String, String> headers, Object params) {
        try {
            if (params instanceof Map) {
                return sendMap(url, headers, (Map<String, Object>) params);
            } else {
                return sendJson(url, headers, (String)params);
            }
        } catch (Exception e){
            return null;
        }
    }

    public static String sendMap(String url, Map<String, String> headers, Map<String, Object> params) throws IOException {
        List<BasicNameValuePair> pairs = new ArrayList<>();
        for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
            String name = iterator.next();
            Object value = params.get(name);
            pairs.add(new BasicNameValuePair(name, String.valueOf(value)));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, UTF8);
        return doAction(url, headers, entity);
    }

    public static String sendJson(String url, Map<String, String> headers, String params) throws IOException {
        StringEntity entity = new StringEntity(params, UTF8);
        return doAction(url, headers, entity);
    }

    private static String doAction(String url, Map<String, String> headers, StringEntity body) throws IOException {
        HttpPut put = new HttpPut(url);
        put.setEntity(body);
        for (String key : headers.keySet()) {
            put.addHeader(key, headers.get(key));
        }

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(put);
        HttpEntity entity = response.getEntity();

        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, UTF8);
        }

        response.close();
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值