安卓OKhttp請求封裝,安卓okhttp封裝

來源:互聯網
上載者:User

安卓OKhttp請求封裝,安卓okhttp封裝

  目前安卓開發中使用的網路工具為OKhttp,但是okhttp的使用還不是很方便,在okhttp的基礎上再對請求進行封裝會極大的方便網路調用。

  下面直接上代碼。

請求封裝
public class HttpUtil {    public static void sendOKHttpRequest(String address, Map<String,String> head,Map<String,String> body,okhttp3.Callback callback){        OkHttpClient client=new OkHttpClient();        Request.Builder builder=new Request.Builder().url(address);        if(head!=null&&head.size()>0){            for (Map.Entry<String, String> entry : head.entrySet()) {                builder.addHeader(entry.getKey(),entry.getValue());            }        }        FormBody.Builder formBody = new FormBody.Builder();        if(body!=null&&body.size()>0){            for (Map.Entry<String, String> entry : head.entrySet()) {                formBody.add(entry.getKey(),entry.getValue());            }        }        RequestBody requestBody = formBody.build();        Request request=builder.post(requestBody).build();        client.newCall(request).enqueue(callback);    }}

上面對okhttp的put請求進行了簡單封裝,四個參數分別是

  1.請求地址

  2.要求標頭,以map的形式傳入,如不需要可傳入null

  3.攜帶參數,同樣以map的形式傳入,如無參數傳入null

  4.回呼函數

代碼中調用

  

     Map<String,String> body=new HashMap<String, String>();     body.put("userName",loginName);     body.put("password",password);

    HttpUtil.sendOKHttpRequest(getString(R.string.ip)+"/xxx/Login",null,body,new Callback(){ @Override public void onFailure(Call call, IOException e) { //請求失敗 } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText=response.body().string(); //請求成功 } });

注意Callback為OKhttp下的,引入時需注意。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.