android网络请求okhttp的使用

来源:互联网 发布:1991莫斯科摇滚知乎 编辑:程序博客网 时间:2024/05/17 08:16

okhttp官网简介:http://square.github.io/okhttp/

okhttp特点:

HTTP/2 support allows all requests to the same host to share a socket.
Connection pooling reduces request latency (if HTTP/2 isn’t available).
Transparent GZIP shrinks download sizes.
Response caching avoids the network completely for repeat requests.

http/2支持允许所有请求共享同一个套接字对于同一个主机
连接池减少请求延迟
Transparent GZIP减小下载大小
响应缓存避免重复的网络请求

ps:

1、从指定的url地址下载,下载的数据以字符串形式输出(get请求方式,get请求方式是默认的请求方式)

import java.io.IOException;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class GetExample {  OkHttpClient client = new OkHttpClient();  String run(String url) throws IOException {    Request request = new Request.Builder()        .url(url)//设置请求地址        .build();    try (Response response = client.newCall(request).execute()) {      return response.body().string();    }  }  public static void main(String[] args) throws IOException {    GetExample example = new GetExample();    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");    System.out.println(response);  }}
2、发送数据到服务器(post请求)
import java.io.IOException;import okhttp3.MediaType;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class PostExample {  public static final MediaType JSON      = MediaType.parse("application/json; charset=utf-8");//定义了MediaType 常量JSON  OkHttpClient client = new OkHttpClient();  String post(String url, String json) throws IOException {    RequestBody body = RequestBody.create(JSON, json);//设置请求体(即发送的数据)    Request request = new Request.Builder()        .url(url)        .post(body)        .build();    try (Response response = client.newCall(request).execute()) {      return response.body().string();    }  }  String bowlingJson(String player1, String player2) {    return "{'winCondition':'HIGH_SCORE',"        + "'name':'Bowling',"        + "'round':4,"        + "'lastSaved':1367702411696,"        + "'dateStarted':1367702378785,"        + "'players':["        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"        + "]}";  }  public static void main(String[] args) throws IOException {    PostExample example = new PostExample();    String json = example.bowlingJson("Jesse", "Jake");    String response = example.post("http://www.roundsapp.com/post", json);    System.out.println(response);  }}







0 0