发送GET请求
OkHttpClient OkHttpGet = new OkHttpClient();
Request requestGet=new Request.Builder().url("https://www.norkm.com/").build();
OkHttpGet.newCall(requestGet).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
/*
* 返回结果
* response.body().string()
* */
}
});
发送POST请求
相比GET请求也只是多了一个post方法,请求参数放置在FormBody.Builder 中。
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("","");
OkHttpClient okHttpPost =new OkHttpClient();
Request requestPost = new Request.Builder().url("https://www.norkm.com/").post(formBody.build()).build();
okHttpPost.newCall(requestPost).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
/*
* 返回结果
* response.body().string()
* */
}
});
发送POST请求,并携带文件上传
OkHttpClient okHttpClientFile = new OkHttpClient();
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File("filePath"));
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("otherName","otherValue")
.addFormDataPart("file", "fileName", fileBody)
.build();
Request uploadRequest = new Request.Builder().url("https://www.norkm.com/").post(requestBody).build();
okHttpClientFile.newCall(uploadRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
/*
* 返回结果
* response.body().string()
* */
}
});
网友评论