OkHttp簡簡簡介,okhttp簡簡

來源:互聯網
上載者:User

OkHttp簡簡簡介,okhttp簡簡
什麼是OKHttp

一般在Java平台上,我們會使用Apache HttpClient作為Http用戶端,用於發送 HTTP 要求,並對響應進行處理。比如可以使用http用戶端與第三方服務(如SSO服務)進行整合,當然還可以爬取網上的資料等。OKHttp與HttpClient類似,也是一個Http用戶端,提供了對 HTTP/2 和 SPDY 的支援,並提供了串連池,GZIP 壓縮和 HTTP 響應緩衝功能;

官網:http://square.github.io/okhttp/

添加依賴

在Java中使用OKHttp很簡單,如果是maven工程,往pom.xml添加如下xml片段即可,目前最新版本2.7.5

<dependency>    <groupId>com.squareup.okhttp</groupId>    <artifactId>okhttp</artifactId>    <version>2.7.5</version></dependency>

如果是gradle,添加如下依賴

compile group: 'com.squareup.okhttp', name: 'okhttp', version: '2.7.5'
 簡單使用後端Controller

一個簡單的spring mvc web應用。

    @RequestMapping(value = "/getUserList", produces = "application/json; charset=utf-8")    @ResponseBody    public String getUserList(int pageNo, int pageSize)    {        Map<String, Object> map = new HashMap<String, Object>();        try        {            Map<String, Object> param = new HashMap<String, Object>();            param.put("pageNo", pageNo);            param.put("pageSize", pageSize);            List<User> userList = userService.queryAll(param);            map.put("userList", userList);            return gson.toJson(map);        }        catch (Exception e)        {            logger.error(e.toString(), e);        }        return gson.toJson(FAILD);    }
使用OkHttp發送Ge請求
package cn.hdu.edu.okhttpdemo;import java.io.IOException;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;/** * Hello world! * */public class App{    public String run(OkHttpClient client, String url) throws IOException {        Request request = new Request.Builder().url(url).build();        Response response = client.newCall(request).execute();        return response.body().string();      }    public static void main( String[] args )    {        OkHttpClient client = new OkHttpClient();        try        {            String res = new App().run(client, "http://localhost:8080/webbf/user/getUserList.do?pageNo=0&pageSize=10");            System.out.println(res);        }        catch (IOException e)        {            e.printStackTrace();        }    }}
使用OkHttp發送Post請求
package cn.hdu.edu.okhttpdemo;import java.io.IOException;import com.squareup.okhttp.FormEncodingBuilder;import com.squareup.okhttp.MediaType;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;/** * Hello world! * */public class App{    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");    public String post(OkHttpClient client, String url) throws IOException    {        Request request = new Request.Builder()        .url(url)        .post(new FormEncodingBuilder()            .add("pageNo", "0")  //參數1            .add("pageSize", "10")  //參數二            .build())        .build();        Response response = client.newCall(request).execute();        return response.body().string();    }    public static void main(String[] args)    {        OkHttpClient client = new OkHttpClient();        try        {            String res = new App().post(client,                "http://localhost:8080/webbf/user/getUserList.do");            System.out.println(res);        }        catch (IOException e)        {            e.printStackTrace();        }    }}
結果列印

請求成功,列印以下資料:

{"userList":[{"id":49,"name":"876","address":"876"},{"id":50,"name":"antd","address":"antd"},{"id":51,"name":"sda","address":"sadsd"},{"id":52,"name":"5545","address":"4646546546"},{"id":53,"name":"sdas","address":"sdasa"},{"id":54,"name":"hggs","address":"sdsd"},{"id":55,"name":"4","address":"5"},{"id":56,"name":"4","address":"4"},{"id":57,"name":"00ba9d8e-0628-4477-857f-ef617c1ff4bc","address":"5906"},{"id":58,"name":"613ee3a3-fb87-4413-a8e0-9272d10ad4a7","address":"6427"}]}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.