1. 程式人生 > >可以傳中文引數的自定義http協議請求方式

可以傳中文引數的自定義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; } }