Brief Introduction to OkHttp and brief introduction to okhttp

Source: Internet
Author: User

Brief Introduction to OkHttp and brief introduction to okhttp
What is OKHttp?

Generally on the Java platform, we use Apache HttpClient as an Http client to send HTTP requests and process the responses. For example, you can use an http client to integrate with a third-party service (such as the SSO Service), or crawl online data. Similar to HttpClient, OKHttp is also an Http client that supports HTTP/2 and SPDY, and provides connection pools, GZIP compression, and HTTP Response caching;

Official Website: http://square.github.io/okhttp/

Add dependency

It is easy to use OKHttp in Java. If it is a maven project, add the following xml snippets to pom. xml. The latest version is 2.7.5.

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

For gradle, add the following dependency:

compile group: 'com.squareup.okhttp', name: 'okhttp', version: '2.7.5'
Easy to use Backend Controller

A simple spring mvc web application.

    @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);    }
Use OkHttp to send Ge requests
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();        }    }}
Use OkHttpSend Post request
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") // parameter 1. add ("pageSize", "10") // parameter 2. build ()). build (); Response response = client.newcall(requestcmd.exe cute (); 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 ();}}}
Result Printing

The request is successful. Print the following data:

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.