可以传中文参数的自定义http协议请求方式

package com.system.util.juxinli;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by chenghongchao on 2017/8/18.
 * Supported By 甜瓜移动.
 * Official Website: www.melonmobile.cn.
 */
public  class JuXinliHttp{

    /**
     * 自定义聚信立post请求方式
     * @param url
     * @param map
     * @return
     */
    public static Map JuXinLiPost(String url,Map map) {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //将接受到的map参数对象转换成字符串到请求对象中
        post.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
        post.addHeader("Content-Type", "application/json; charset=utf-8");
        post.setHeader("Accept", "application/json");
        //执行请求操作,并拿到结果
        try {
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity,"utf-8");
            }
            EntityUtils.consume(entity);
            //释放
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json=JSONObject.parseObject(body);
        return json;
    }
    /***
     * 自定义聚信立get请求方式
     * @param url
     * @return
     */
    public  static Map JuXinLiGet(String url){
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get=new HttpGet(url);
        get.addHeader("Content-Type", "application/json; charset=utf-8");
        get.setHeader("Accept", "application/json");
        try {
            CloseableHttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity,"utf-8");
            }
            EntityUtils.consume(entity);
            //释放
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json=JSONObject.parseObject(body);
        return json;
    }
}


你可能感兴趣的:(后端,maven)