项目中,我们需要和服务器进行大量的交互,其中最为频繁地就是Get方式和Post方式,下面就将主流的网络框架Okhttp的
Get方式和Post方式的使用做一下介绍:
1.Get方式:
OkHttpClient okHttpClient = new OkHttpClient .Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10,TimeUnit.SECONDS) .writeTimeout(10,TimeUnit.SECONDS) .build(); Request request = new Request .Builder() .url(Constants.GET_USER_ADDRESS_URL + url) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Utils.runOnUIThread(new Runnable() { @Override public void run() { Toast.makeText(DeliveryAddressActivity.this,Constants.CONNECTION_TIMEOUT,Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String s = response.body().string(); Log.e("add",s); GetAddressListResponse getAddressListResponse = GsonUtils.paserJsonToBean(s,GetAddressListResponse.class); Message msg = new Message(); msg.what = 1; msg.obj = getAddressListResponse; handler.sendMessage(msg); } });
需要注意几点:请求网络超时需要在onFailure()方法中进行处理,请求成功后需要用到Handler机制。
2.Post方式:
OkHttpClient okHttpClient = new OkHttpClient .Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10,TimeUnit.SECONDS) .writeTimeout(10,TimeUnit.SECONDS) .build(); RequestBody requestBody = new FormBody.Builder() .add("username",userName) .add("oldPwdMD5",MD5Tools.md5(etOldPsw.getText().toString()).toUpperCase()) .add("newPwdMD5",MD5Tools.md5(etNewPsw.getText().toString()).toUpperCase()) .build(); Request requestPost = new Request.Builder() .url(Constants.CHANGE_USER_PSW_URL + "appid=" + Constants.APP_ID_S + "&encrypt=" + encrypt) .post(requestBody) .build(); okHttpClient.newCall(requestPost).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Utils.runOnUIThread(new Runnable() { @Override public void run() { Toast.makeText(ModifyPswActivity.this,Constants.CONNECTION_TIMEOUT,Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String s = response.body().string(); Log.e("changePsw",s); ChangePswResponse changePswResponse = GsonUtils.paserJsonToBean(s,ChangePswResponse.class); Message msg = new Message(); msg.what = 1; msg.obj = changePswResponse; handler.sendMessage(msg); } });特别提示:请求体中的值无需encode。