RequestBody.create 接收封装的json数据
MediaType.parse(“application/json”) 上传json文件的类型
findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OkHttpClient okHttpClient = new OkHttpClient();
//MediaType.parse("application/json")封装上传文件的类型和json数据
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), "{\"a\":1,\":2}");
Request request =new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {//判断是否返回成功
Log.i("TAG", "Get异步请求" + response.body().string());
}
}
});
}
});