okhttp3.OkHttpClient Get带头部Headers,带参数请求

package com.bonade.hrm.attendance.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.bonade.hrm.common.util.EmptyUtils;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OK3HttpClient {
	private static final Logger log = LoggerFactory.getLogger(OK3HttpClient.class);

	public static String httpGet(String url, Map params, Map headMap) {
		// 设置HTTP请求参数
		String result = null;
		url += getParams(params);
		Headers setHeaders = SetHeaders(headMap);
		OkHttpClient okHttpClient = new OkHttpClient();
		Request request = new Request.Builder().url(url).headers(setHeaders).build();
		Call call = okHttpClient.newCall(request);
		try {
			Response response = call.execute();
			String string = response.body().string();
			result = String.valueOf(JSON.parse(string));
		} catch (Exception e) {
			log.error("调用三方接口出错", e);
		}
		return result;
	}

	public static String getParams(Map params) {
		StringBuffer sb = new StringBuffer("?");
		if (EmptyUtils.isNotEmpty(params)) {
			for (Map.Entry item : params.entrySet()) {
				Object value = item.getValue();
				if (EmptyUtils.isNotEmpty(value)) {
					sb.append("&");
					sb.append(item.getKey());
					sb.append("=");
					sb.append(value);
				}
			}
			return sb.toString();
		} else {
			return "";
		}
	}

	public static Headers SetHeaders(Map headersParams) {
		Headers headers = null;
		okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
		if (EmptyUtils.isNotEmpty(headersParams)) {
			Iterator iterator = headersParams.keySet().iterator();
			String key = "";
			while (iterator.hasNext()) {
				key = iterator.next().toString();
				headersbuilder.add(key, headersParams.get(key));
			}
		}
		headers = headersbuilder.build();
		return headers;
	}

	public static void main(String[] args) {
		
		
	}
}

 

 

 

你可能感兴趣的:(Java)