android開發 之OkHttp二次封裝(android 訪問網路)
阿新 • • 發佈:2018-12-17
這個是本人在使用的一個網路請求,根據自己的需求進行修改的,對於自己完全夠用。大家有需要可以根據自己的專案修改成自己需要的。如果有什麼問題,還希望告知。
使用時繼承該類即可
import android.os.Handler; import android.os.Message; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by xiaobao on 2018/9/24. */ public abstract class HttpBase { private String url="192.168.1.1";//伺服器地址 private Handler handler; private int SuccessCode;//成功時message.what //post方法需要重寫此方法 public FormBody setFormBody(FormBody formBody){ formBody = new FormBody.Builder() //.add("type","addshop") .build(); return formBody; } //post訪問網路 public void httpPost (String urls, final Handler handler, final int SuccessCode) { //開啟網路請求 this.handler=handler; this.SuccessCode=SuccessCode; OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); FormBody formBody = null; formBody=setFormBody(formBody); String tempurl=urls.startsWith("http")?urls:url+urls; final Request request = new Request.Builder() .url(tempurl)//請求的url .post(formBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //將空字串給子類處理,例項化某些資料,防止出現空指標異常,本人專案需要,大家可自行修改 sendMessage(""); } @Override // 獲取到伺服器資料。注意:即使是 404 等錯誤狀態也是獲取到伺服器資料 public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ String rerStr=response.body().string(); sendMessage(rerStr); } } }); } //get訪問網路 public void HttpGet(String urls, final Handler handler, final int SuccessCode) { this.handler=handler; this.SuccessCode=SuccessCode; OkHttpClient okHttpClient = new OkHttpClient(); String tempurl=urls.startsWith("http")?urls:url+urls; Request request = new Request.Builder().url(tempurl).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Msg msg=new Msg(5000,"伺服器通訊異常,請檢查網路是否可用"); // messages(msg); // String rerStr=response.body().string(); sendMessage(""); } @Override // 獲取到伺服器資料。注意:即使是 404 等錯誤狀態也是獲取到伺服器資料 public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ String rerStr=response.body().string(); sendMessage(rerStr); } } }); } //實現該方法對返回資料進行處理 public abstract void sendMessage(String reStr) ; //將處理好的資訊返回 public void messages( Object object){ Message message=new Message(); message.what=SuccessCode; message.obj=object; handler.sendMessage(message); } }
get方法呼叫演示
UserEntity 是使用者實體,這裡就不給出了
url連結如果不是http開頭,那麼會使用httpBase裡面的url地址
public class LoginHttp extends HttpBase { //使用時呼叫此方法 public void login(Handler handler, String username, String password) { String url = "/api/user/login?username="+username+"&password="+password; super.HttpGet(url, handler, 0x200); } //處理返回資料 @Override public void sendMessage(String reStr) { UserEntity userEntity = new UserEntity(); try { JSONObject jsonObject = new JSONObject(reStr); int code = jsonObject.getInt("code"); userEntity.setCode(code); userEntity.setMsg(jsonObject.getString("msg")); if (code == 1000) { userEntity.setUsername(jsonObject.getString("username")); userEntity.setPhone(jsonObject.getString("phone")); } } catch (JSONException e) { e.printStackTrace(); } super.messages(userEntity); } }
post方法呼叫演示
import android.os.Handler; import android.os.Message; import org.json.JSONException; import org.json.JSONObject; import cn.mvapi.daogouba.entity.Msg; import cn.mvapi.daogouba.ui.BaseActivity; import okhttp3.FormBody; /** * Created by 小寶 on 2018/10/23. */ public class HeadImgHttp extends HttpBase{ private String imgbase; private String imgname; //使用時呼叫次方法 public void upImg(Handler handler, String imgbase,String imgname) { this.imgbase = imgbase; this.imgname=imgname; super.httpPost("/api/user/upload", handler, 0x200); } //處理返回資料 @Override public void sendMessage(String reStr) { Msg msg=new Msg(); try { JSONObject jsonObject=new JSONObject(reStr); msg.setCode(jsonObject.getInt("code")); msg.setMsg(jsonObject.getString("msg")); } catch (JSONException e) { e.printStackTrace(); } super.messages(msg); } //引數傳遞 @Override public FormBody setFormBody(FormBody formBody) { formBody = new FormBody.Builder() .add("imgStr", imgbase) .add("imgname",imgname) .build(); return formBody; } }