跳至主要内容

android java 使用OKHttp3 get请求 , post请求 , 多文件上传 , 包看包会

1 首先需要创建一个OKHttpClient 
可以直接new一个  
[java] view plain copy
  1. OkHttpClient client = new OkHttpClient()  

更多的是用builder构造一个 (那个addInterceptor方法是添加拦截器 , 可以不写,具体的baidu, bing, sogou)
[java] view plain copy
  1. private void buildHttpClient(){  
  2.         this.client = new OkHttpClient.Builder()  
  3.                 .addInterceptor(new Interceptor() {  
  4.                     public Response intercept(Chain chain) throws IOException {  
  5.                         Request request = chain.request();  
  6.                         Response response = chain.proceed(request);  
  7.                         return response;  
  8.                     }  
  9.                 })  
  10.                 .connectTimeout(4000, TimeUnit.MILLISECONDS)  
  11.                 .readTimeout(4000,TimeUnit.MILLISECONDS)  
  12.                 .writeTimeout(4000, TimeUnit.MILLISECONDS)  
  13.                 .build();  
  14. }  


2 GET 请求
[java] view plain copy
  1. <strong>    </strong>private void get(){  
  2.         /* 如果需要参数 , 在url后边拼接 :  ?a=aaa&b=bbb..... */  
  3.         Request request = new Request.Builder().url("http://192.168.10.117:8080/test").build();  
  4.         client.newCall(request).enqueue(new Callback() {  
  5.             public void onResponse(Call call, final Response response) throws IOException {  
  6.                 final String result = response.body().string();  
  7.                 final boolean ok = response.isSuccessful();  
  8.                 runOnUiThread(new Runnable() {  
  9.                     public void run(){  
  10.                         Toast.makeText(OKHttpActivity.this, result, Toast.LENGTH_SHORT).show();  
  11.                     }  
  12.                 });  
  13.             }  
  14.             public void onFailure(Call call, IOException e) {  
  15.                 runOnUiThread(new Runnable() {  
  16.                     public void run() {  
  17.                         Toast.makeText(OKHttpActivity.this"error", Toast.LENGTH_SHORT).show();  
  18.                     }  
  19.                 });  
  20.             }  
  21.         });  
  22.     }  

3 POST 请求
[java] view plain copy
  1. private void post(){  
  2.     FormBody.Builder builder = new FormBody.Builder();  
  3.     /* 添加两个参数 */  
  4.     builder.add("p","我勒个去").add("a","hello");  
  5.     FormBody body = builder.build();  
  6.     Request request = new Request.Builder().url("http://192.168.10.117:8080/test").post(body).build();  
  7.   
  8.     /* 下边和get一样了 */  
  9.     client.newCall(request).enqueue(new Callback() {  
  10.         public void onResponse(Call call, Response response) throws IOException {  
  11.             final  String bodyStr = response.body().string();  
  12.             final boolean ok = response.isSuccessful();  
  13.             runOnUiThread(new Runnable() {  
  14.                 public void run() {  
  15.                     if(ok){  
  16.                         Toast.makeText(OKHttpActivity.this, bodyStr, Toast.LENGTH_SHORT).show();  
  17.                     }else{  
  18.                         Toast.makeText(OKHttpActivity.this"server error : " + bodyStr, Toast.LENGTH_SHORT).show();  
  19.                     }  
  20.                 }  
  21.             });  
  22.         }  
  23.         public void onFailure(Call call,final IOException e) {  
  24.             runOnUiThread(new Runnable() {  
  25.                 public void run() {  
  26.                     Toast.makeText(OKHttpActivity.this"error : "+e.toString(), Toast.LENGTH_SHORT).show();  
  27.                 }  
  28.             });  
  29.         }  
  30.     });  
  31. }  

4 多文件上传
[java] view plain copy
  1. private void upFile(){  
  2.     /* 第一个要上传的file */  
  3.     File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");  
  4.     RequestBody fileBody1 = RequestBody.create(MediaType.parse("application/octet-stream") , file1);  
  5.     String file1Name = "testFile1.txt";  
  6.   
  7.     /* 第二个要上传的文件,这里偷懒了,和file1用的一个图片 */  
  8.     File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");  
  9.     RequestBody fileBody2 = RequestBody.create(MediaType.parse("application/octet-stream") , file2);  
  10.     String file2Name = "testFile2.txt";  
  11.   
  12.   
  13.     /* form的分割线,自己定义 */  
  14.     String boundary = "xx--------------------------------------------------------------xx";  
  15.   
  16.     MultipartBody mBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)  
  17.             /* 上传一个普通的String参数 , key 叫 "p" */  
  18.             .addFormDataPart("p" , "你大爷666")  
  19.             /* 底下是上传了两个文件 */  
  20.             .addFormDataPart("file" , file1Name , fileBody1)  
  21.             .addFormDataPart("file" , file2Name , fileBody2)  
  22.             .build();  
  23.   
  24.     /* 下边的就和post一样了 */  
  25.     Request request = new Request.Builder().url("http://192.168.10.117:8080/test").post(mBody).build();  
  26.     client.newCall(request).enqueue(new Callback() {  
  27.         public void onResponse(Call call, Response response) throws IOException {  
  28.             final  String bodyStr = response.body().string();  
  29.             final boolean ok = response.isSuccessful();  
  30.             runOnUiThread(new Runnable() {  
  31.                 public void run() {  
  32.                     if(ok){  
  33.                         Toast.makeText(OKHttpActivity.this, bodyStr, Toast.LENGTH_SHORT).show();  
  34.                     }else{  
  35.                         Toast.makeText(OKHttpActivity.this"server error : " + bodyStr, Toast.LENGTH_SHORT).show();  
  36.                     }  
  37.                 }  
  38.             });  
  39.         }  
  40.         public void onFailure(Call call, final IOException e) {  
  41.             runOnUiThread(new Runnable() {  
  42.                 public void run() {  
  43.                     Toast.makeText(OKHttpActivity.this, e.toString(), Toast.LENGTH_SHORT).show();  
  44.                 }  
  45.             });  
  46.         }  
  47.     });  
  48. }  

评论

此博客中的热门博文

onsen ui example splitter side menu swipe

<!DOCTYPE html> <html> <head> <title>TheyTube - Watch free video online</title> <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css"> <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">   <script src="https://unpkg.com/onsenui/js/onsenui.min.js"></script>   <script type="text/javascript">   ons.platform.select('android')   </script> </head> <body> <ons-splitter>   <ons-splitter-side id="menu" side="left" width="220px" collapse swipeable>     <ons-page>       <ons-list>         <ons-list-item onclick="fn.load('home.html')" tappable>           Home         </ons-list-item>         <ons-list-item onclick="fn.load('settings.html')" tappable>           Setti

go golang get disk usage free space remain info

package main import ( "fmt" "syscall" ) func main() { fmt.Println(DiskUsage("./")) } func DiskUsage(path string) uint64 { fs := syscall.Statfs_t{} err := syscall.Statfs(path, &fs) if err != nil { return 0 } return fs.Bfree * uint64(fs.Bsize) } //All space   = fs.Blocks * uint64(fs.Bsize) //Free space = fs.Bfree * uint64(fs.Bsize) //Used space= fs.All - disk.Free