HTTP请求工具java

package com.xxx.mid.utils;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Component
public class OkHttpUtil {
	private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
	@Resource
	private OkHttpClient okHttpClient;

	/**
	 * post
	 *
	 * @param url
	 *            请求的url
	 * @param params
	 *            post form 提交的参数
	 * @return
	 */
	public String post(String url, Map<String, String> params) {
		FormBody.Builder builder = new FormBody.Builder();
		// 添加参数
		if (params != null && params.keySet().size() > 0) {
			for (String key : params.keySet()) {
				builder.add(key, params.get(key));
			}
		}
		Request request = new Request.Builder().url(url).post(builder.build()).build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp3 post error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * get
	 * 
	 * @param url
	 *            请求的url
	 * @param queries
	 *            请求的参数,在浏览器?后面的数据,没有可以传null
	 * @return
	 */
	public String getForHeader(String url, Map<String, String> queries) {
		StringBuffer sb = new StringBuffer(url);
		if (queries != null && queries.keySet().size() > 0) {
			boolean firstFlag = true;
			Iterator<Entry<String, String>> iterator = queries.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
				if (firstFlag) {
					sb.append("?" + entry.getKey() + "=" + entry.getValue());
					firstFlag = false;
				} else {
					sb.append("&" + entry.getKey() + "=" + entry.getValue());
				}
			}
		}
		Request request = new Request.Builder().addHeader("key", "value").url(sb.toString()).build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp3 put error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一:请求Url 参数二:请求的JSON
	 * 参数三:请求回调
	 */
	public String postJsonParams(String url, String jsonParams) {
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
		Request request = new Request.Builder().url(url)
				//.addHeader("Accept-Encoding", "gzip, deflate")
				.addHeader("Content-Type", "application/json;charset=utf-8")
				.addHeader("Connection", "keep-alive")
				.post(requestBody).build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp3 post error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * Post请求发送xml数据.... 参数一:请求Url 参数二:请求的xmlString 参数三:请求回调
	 */
	public String postXmlParams(String url, String xml) {
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
		Request request = new Request.Builder().url(url)
				.addHeader("Content-Type", "application/xml; charset=UTF-8")
				.header("Accept-Encoding", "gzip, deflate")
				.addHeader("Connection", "keep-alive").post(requestBody)
				.build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp3 post error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * get
	 *
	 * @param url
	 *            请求的url
	 * @param queries
	 *            请求的参数,在浏览器?后面的数据,没有可以传null
	 * @return
	 */
	public String get(String url, Map<String, String> queries) {
		StringBuffer sb = new StringBuffer(url);
		if (queries != null && queries.keySet().size() > 0) {
			boolean firstFlag = true;
			Iterator<Entry<String, String>> iterator = queries.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
				if (firstFlag) {
					sb.append("?" + entry.getKey() + "=" + entry.getValue());
					firstFlag = false;
				} else {
					sb.append("&" + entry.getKey() + "=" + entry.getValue());
				}
			}
		}
		Request request = new Request.Builder().url(sb.toString()).build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (status == 200) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp put error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * post 上传文件
	 *
	 * @param url
	 * @param params
	 * @param fileType
	 * @return
	 */
	public String postFile(String url, Map<String, Object> params, String fileType) {
		MultipartBody.Builder builder = new MultipartBody.Builder();
		// 添加参数
		if (params != null && params.keySet().size() > 0) {
			for (String key : params.keySet()) {
				if (params.get(key) instanceof File) {
					File file = (File) params.get(key);
					builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
					continue;
				}
				builder.addFormDataPart(key, params.get(key).toString());
			}
		}
		Request request = new Request.Builder().url(url).post(builder.build()).build();
		Response response = null;
		try {
			response = okHttpClient.newCall(request).execute();
			int status = response.code();
			if (status == 200) {
				return response.body().string();
			}
		} catch (Exception e) {
			logger.error("okhttp postFile error >> ex = {}", e.getMessage());
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值