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;
}
}