1 public class MainActivity extendsAppCompatActivity {2
3 @Override4 protected voidonCreate(Bundle savedInstanceState) {5 super.onCreate(savedInstanceState);6 setContentView(R.layout.activity_main);7 }8
9 //基本请求默认GET请求
10 public voidnet1(View v){11 //可以通过构造方法来使用。使用Builder模式可以设置一些属性12 //OkHttpClient client = new OkHttpClient();13 //缓存的请求的数据,json字符串,14 //Cache questCache = new Cache(new File("cache"),1024);
15 OkHttpClient client = newOkHttpClient.Builder()16 //读取超时5s
17 .readTimeout(5000, TimeUnit.MILLISECONDS)18 //自带缓存,缓存可做可不做,做了就是让刷新的时候方便些,不会重复去请求同一个url多次19 //.cache(questCache)
20 .build();21
22 //默认GET请求
23 Request request = newRequest.Builder()24 .url("https://www.baidu.com")25 .build();26
27 //call就是我们可以执行的请求类
28 Call call =client.newCall(request);29
30
31 //try {32 // //同步方法,程序运行到这里会等待,所以这里我们不用这个方法33 //Response execute = call.execute();34 //} catch (IOException e) {35 //e.printStackTrace();36 //}37
38 //异步请求
39 call.enqueue(newCallback() {40 @Override41 public voidonFailure(Call call, IOException e) {42 Log.e("TAG","请求失败");43 }44
45 @Override46 public void onResponse(Call call, Response response) throwsIOException {47 //子线程
48 Log.e("TAG",Thread.currentThread().getName()+"---结果:"+response.body().string());49 //修改UI使用 runOnUiThread();或者使用Handler发送更新UI消息给主线程
50 }51 });52
53 //取消54 //call.cancel();
55 }56
57 //POST请求
58 public voidnet2(View v){59 OkHttpClient client = newOkHttpClient.Builder()60 .readTimeout(5000,TimeUnit.MILLISECONDS)61 .build();62
63 //创建Form表单对象,可以add多个键值对
64 RequestBody body = newFormBody.Builder()65 .add("showapi_appid","27306")66 .add("showapi_sign","150e9206e7f542bab4affe49d73cb920")67 .build();68
69 Request request = new Request.Builder().url("http://route.showapi.com/578-6")70 .post(body)//添加参数
71 .build();72
73 Call call =client.newCall(request);74 call.enqueue(newCallback() {75 @Override76 public voidonFailure(Call call, IOException e) {77 Log.e("TAG","请求失败");78 }79
80 @Override81 public void onResponse(Call call, Response response) throwsIOException {82 Log.e("TAG","---->"+response.toString());83 //子线程
84 }85 });86
87 }88
89 //文件上传
90 public voidnet3(View v){91 OkHttpClient client = newOkHttpClient.Builder()92 .readTimeout(5000,TimeUnit.MILLISECONDS)93 .build();94
95 //添加多个文件
96 RequestBody fileBody = MultipartBody.create(MediaType.parse("application/octet-stream"),new File("上传的文件地址"));97
98
99 RequestBody body = newMultipartBody.Builder()100 //设置为表单类型
101 .setType(MultipartBody.FORM)102 //添加表单键值
103 .addFormDataPart("image头像字段名称","name文件名称",fileBody)104 .build();105
106 Request request = newRequest.Builder()107 .url("http://192.168.18.250")108 .post(body)109 .build();110
111 Call call =client.newCall(request);112 call.enqueue(newCallback() {113 @Override114 public voidonFailure(Call call, IOException e) {115
116 }117
118 @Override119 public void onResponse(Call call, Response response) throwsIOException {120 //子线程
121 }122 });123 }124 }