一、GET方式请求数据
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().get().url("http://v.juhe.cn/toutiao/index?type=top&key=57eee480312cb6c613c50237e7ba325b").build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("myTag", "请求失败" + e.getLocalizedMessage() + "===" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String json = response.body().string();
Log.i("myTag", "请求成功--》" + json);
}
if (response.body() != null) {
response.body().close();
}
}
});
二 、POST方式请求(Form表单的形式)
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder().add("type", "").add("key", "57eee480312cb6c613c50237e7ba325b").build();
Request request = new Request.Builder().url("http://v.juhe.cn/toutiao/index").post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("myTag", "请求失败" + e.getLocalizedMessage() + "===" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String json = response.body().string();
Log.i("myTag", "请求成功--》" + json);
}
if (response.body() != null) {
response.body().close();
}
}
});
三、POST方式请求(json参数形式)
OkHttpClient okHttpClient = new OkHttpClient();
JSONObject object = new JSONObject();
try {
object.put("name","123");
object.put("pw","123");
} catch (JSONException e) {
e.printStackTrace();
}
String json = object.toString();
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json);
Request request = new Request.Builder().url("http://v.juhe.cn/toutiao/index").post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("myTag", "请求失败" + e.getLocalizedMessage() + "===" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String json = response.body().string();
Log.i("myTag", "post-form 请求成功--》" + json);
}
if (response.body() != null) {
response.body().close();
}
}
});