java OkHttp请求


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import net.sf.json.JSONObject;

/**
 * http请求
 * @author taihei
 *
 */
public class OkHttpReq {

	/**
	 * post请求
	 * @param uri 地址
	 * @param params 参数
	 * @return
	 */
	public JSONObject reqHttpPost(String uri, Map<String, String> params) {
		JSONObject paramsJson = JSONObject.fromObject(params);
		OkHttpClient client = new OkHttpClient();

		MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
		RequestBody body = RequestBody.create(mediaType, paramsJson.toString());
		Request request = new Request.Builder().url(uri).post(body)
				.addHeader("content-type", "application/json;charset=utf-8").addHeader("accept", "application/json")
				.build();

		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String respon = new String(response.body().string());
				return JSONObject.fromObject(respon);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * get请求
	 * @param uri 地址
	 * @param params 参数
	 * @return
	 */
	public String reqHttpGet(String uri, Map<String, String> params) {
		Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator();
		StringBuffer urlParamsBuffer = new StringBuffer();
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = iter.next();
			try {
				urlParamsBuffer.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8") + "&");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		String getUrl = uri;
		if (urlParamsBuffer.length() > 0) {
			urlParamsBuffer.deleteCharAt(urlParamsBuffer.length() - 1);
			getUrl += '?' + urlParamsBuffer.toString();
		}

		OkHttpClient client = new OkHttpClient();

		Request request = new Request.Builder()
				.url(getUrl)
				.get()
				.addHeader("accept", "application/json")
				.addHeader("cache-control", "no-cache").build();

		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				String respon = new String(response.body().string());
//				System.out.println(respon);
				return respon;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}

 

转载于:https://my.oschina.net/2892328252/blog/829075

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值