Kong Jing

okhttp的操作使用经验

23 June 2016

足球,不是生命,但高于生命!足球,不是生活的全部,却就是生活本身!我热爱足球运动,从年少成长的历程到岁月经历的坎坷从未让我忘掉热爱它的初心。足球,其实很简单,朴素而本色的奔跑,追逐心中的梦想,胜利的雀跃与失败的沮丧交织中,汗泪涅槃!足球也很复杂,没有坚定的信念与咬牙的坚持以及良好的协作精神是踢不出真正的足球韵味的!因为足球不仅是个人表演的舞台,也更是团队无私奉献的战场,,没有硝烟,但充满勇气并拥有尊重和友谊!人生不正是如此么?或许你会有孤独,没有喝采与欢呼,但你的付出与坚持让你永远不会独行!我热爱足球,我的生活,我的荣幸。
—大黄

square公司有很多高质量的开源项目,okhttp是被广泛使用的一种框架。 最近开发中使用到了这个工具,所以在这里写下这些经验。 OKHttp的请求数据与接收方式有多种,我最近使用的是Posting form parameters, 业务中使用map将key与value都传入其中,然后进行数据的传送。

官方的github地址 https://github.com/square/okhttp

gradle的配置文件

compile 'com.squareup.okhttp3:okhttp:3.3.1'
使用Http Get的代码如下

package okhttp3.guide;
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);
  }
}


使用 Post的方法的代码

package okhttp3.guide;
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");

  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);
  }
}
try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }

这里的代码需要使用API19以上,是jdk7的新特性,可以选择使用

Response response = client.newCall(request).execute()
try{
  return response.body().string();
  }finally{
    if(null != response){
      response.close();
    }
  }

个人使用中用到的Posting form parameters方式

    OkHttpClient client = new OkHttpClient();
    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        FormBody.Builder formBuilder = new FormBody.Builder();
        while (iterator.hasNext()) {

            Map.Entry<String, String> entry = iterator.next();
            formBuilder.add(entry.getKey(),entry.getValue());
        }

        RequestBody body = formBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

— Kong Jing