转载自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html
部分:
HTTP GET
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string();
} else { throw new IOException("Unexpected code " + response);
}
}
HTTP POST
POST提交Json数据
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
使用Request的post方法来提交请求体RequestBody