okhttp3

//文件上传  
   String baseUrl = "http://localhost:9000/file"; File file = new File("E:/girl.jpg"); OkHttpClient okHttpClient = new OkHttpClient(); RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); MultipartBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data")) .addFormDataPart("file", file.getName(), fileBody).build(); Request request = new Request.Builder().post(body).url(baseUrl).build(); long start = new Date().getTime(); okHttpClient.newCall(request).execute().body().string(); long end = new Date().getTime(); System.out.println("use "+(end-start));

 

//下载文件
OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder=new Request.Builder().url(url); okHttpClient.newCall(builder.build()).enqueue(new Callback() { public void onResponse(Call arg0, Response arg1) throws IOException { // TODO Auto-generated method stub System.out.println("onResponse"); InputStream is = arg1.body().byteStream(); File file=new File("e:/down.png"); int len=-1; byte[] buffer=new byte[1024]; FileOutputStream fileOutputStream=new FileOutputStream(file); while((len=is.read(buffer))>0) { fileOutputStream.write(buffer, 0, len); } } public void onFailure(Call arg0, IOException arg1) { // TODO Auto-generated method stub System.out.println("onFailure"); } });

 

//post json ,header添加参数
OkHttpClient okHttpClient =new OkHttpClient(); Request.Builder requetBuilder=new Request.Builder(); requetBuilder.addHeader("token", "33344"); RequestBody requestBody=RequestBody.create("{\"name\":\"rrrrxxxng\",\"sex\":30,\"id\":2}",MediaType.parse("application/json")); try { Response result = okHttpClient.newCall( requetBuilder.url(baseUrl).post(requestBody).build()).execute(); System.out.println(result.body().string()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

 

你可能感兴趣的:(okhttp3)