程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> OkHttp簡簡簡介,okhttp簡簡

OkHttp簡簡簡介,okhttp簡簡

編輯:JAVA綜合教程

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"}]}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved