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();
if(response.isSuccessful()){
return response.body().string();}else{}
3 http文件上传
一个可以构造RequestBody的builder 叫做MultipartBuilder 当我们需要做类似于表单的上传上传的时候就可以用这个File file = new File(Environment.getExternalStorageDirectory(),"demo.mp4");RequestBody fileBody = RequestBody.create(MeidaType.parse("application/octet-stream"), file));RequestBody requestbody = new MultipartBuilder().type(MultipartBuilder.FORm) .addPart(Headers.of( "Content-Disposition","form-data; name=/"username/""), RequestBody.create(null,"123")) .addPart(Headers.of( "Content-Disposition","form-data; name=/"mFile/"; filename=/"wjd.mp4/""), fileBody) .build();Request request = new Request.Builder().url(url).post(requestbody).build();Call call = new OkhttpClient().newCall(request);call.enqueue(new Callback(){});这段代码是向服务器传递了一个键值对username:123和一个视频文件,MultipartBuilder的addPart方法可以添加键值对或者文件4 文件下载下载一个文件 用string形式打印响应体 如果小文档可以十分方便如果太大不要使用这个方法需要使用流的方式来处理bodyPRivate final OkhttpClient client = new OkhttpClient();public void run()throws Exception{Rquest request = new Requst.Builder().url(url).build();Response response = client.newCall(request).execute();if(!response.isSuccessful())throw new IOException(""+response);Headers res= response.headers();for(int i=0;i<res.size();i++){syso(res.name(i)+":"+res.value(i));}syso(res.body().string);}也可以client.newCall(request).enqueue(new Callback(){onFilure(){throwable.printStackTrace();}onResponse(){if(!response.isSuccessful())throw new IOException(""+response);Headers res= response.headers();for(int i=0;i<res.size();i++){syso(res.name(i)+":"+res.value(i));}syso(res.body().string);}});转载来自:张鸿洋博客 和泡在网上的日子的文章