import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;java
import org.apache.commons.lang.StringUtils;apache
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;json
/**
* OkHttpclient請求處理類
* 2018年12月19日
*/
public class OkHttpClientUtil {
//默認請求的文本參數類型
private static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String DEFAULT_CACHE_CTRL = "no-cache";
/**
* 發送請求
* 2018年12月19日
* @param url 必傳,訪問接口的url
* @param contentType 非必傳,默認爲urlEncoded
* @param parameters 必傳,消息體類型
* @param headers 必傳,消息頭格式設置
* @return 成功響應後的內容字符串:異常結果爲null
* @throws Exception
*/
public static JSONObject sendPost(String url,String contentType,Map<String,Object> parameters, Map<String,String> headers) throws Exception {
if (StringUtils.isBlank(contentType)) {
contentType = DEFAULT_CONTENT_TYPE;
}
//構建client,處理入參
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse(contentType);
RequestBody body = RequestBody.create(mediaType, convertMap2Str(parameters));
//設置消息頭
Builder builder = new Request.Builder().url(url).post(body);
builder.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
builder.addHeader("cache-control", DEFAULT_CACHE_CTRL);
//若是headers不爲空,從新設置消息頭
if (headers != null && !headers.isEmpty()) {
for(Entry<String,String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
//創建鏈接,發送請求
Request request = builder.build();
Response response = client.newCall(request).execute();
//返回json格式數據,帶成功失敗碼
JSONObject result = new JSONObject();
result.put("code", response.code());
if (response.code() == 200) {
ResponseBody rb = response.body();
InputStream in = rb.byteStream();
//從流中解析結構並返回
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
result.put("result", responseStrBuilder.toString());
} else {
result.put("message", response.message());
}
return result;
}
/**
* 將map參數轉換成string
* 2018年12月19日
* @param inMap
* @return
*/
public static String convertMap2Str(Map<String,Object> inMap) {
if (!(inMap instanceof TreeMap)) {
inMap = new TreeMap<>(inMap);
}
StringBuffer sb = new StringBuffer();
for(Entry<String,Object> entry : inMap.entrySet()) {
Object value = entry.getValue();
sb.append(entry.getKey()).append("=").append(value).append("&");
}
if(sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}app