OkHttpClient详解

【温馨小提示】:
再用okHttpClient时,最好定义成static型

private static OkHttpClient okHttpClient;
static {
    okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();
}

HTTP GET

OkHttpClient client = new OkHttpClient();
 
String run(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();    if (response.isSuccessful()) {        return response.body().string();
    } else {        throw new IOException("Unexpected code " + response);
    }
}

HTTP POST

POST提交Json数据

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();
      Response response = client.newCall(request).execute();
    f (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

POST提交键值对

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
 
     RequestBody formBody = new FormEncodingBuilder()
    .add("platform", "android")
    .add("name", "bug")
    .add("subject", "XXXXXXXXXXXXXXX")
    .build();
 
      Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
 
      Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

post提交form-data

public List getPolyvToken(HzsPolyvsList polyvsList) {
        List polyvTokenEntityList = new ArrayList<>();
        List polyvDetailsList = polyvsList.getHzsPolyvDetailsList();
        for(HzsPolyvDetails polyvDetails : polyvDetailsList) {
            StringBuilder concated = new StringBuilder().append(secretkey);
            concated.append("extraParams").append(polyvDetails.getExtraParams())
                    .append("ts").append(polyvDetails.getTs())
                    .append("userId").append(secretId)
                    .append("videoId").append(polyvDetails.getVideoId())
                    .append("viewerId").append(polyvDetails.getUserId())
                    .append("viewerIp").append(polyvDetails.getIp())
                    .append("viewerName").append(polyvDetails.getUsername()).append(secretkey);

            String sign = this.MD5Code(concated.toString().trim());

            OkHttpClient client = new OkHttpClient();
            FormBody body = new FormBody.Builder()
                    .add("userId", secretId)
                    .add("videoId", polyvDetails.getVideoId())
                    .add("ts", String.valueOf(polyvDetails.getTs()))
                    .add("viewerIp", polyvDetails.getIp())
                    .add("viewerName", polyvDetails.getUsername())
                    .add("extraParams", polyvDetails.getExtraParams())
                    .add("viewerId", String.valueOf(polyvDetails.getUserId()))
                    .add("sign", sign)
                    .build();
            Request request = new Request.Builder().addHeader("Content-type", "application/x-www-form-urlencoded")
                    .url(url).post(body)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if(response.isSuccessful()) {
                    String result = response.body().string();
                    logger.debug("****************content:" + result);
                    Document document = Document.parse(result);
                    Document document1 = (Document) document.get("data");
                    HzsPolyvTokenEntity polyvTokenEntity1 = new HzsPolyvTokenEntity();
                    polyvTokenEntity1.setToken(document1.get("token").toString());
                    polyvTokenEntity1.setVideoId(document1.get("videoId").toString());
                    polyvTokenEntityList.add(polyvTokenEntity1);
                    return polyvTokenEntityList;
                } else {
                    logger.debug("*********" + response.body().string());
                    throw new IllegalArgumentException("get polyv interface failed!");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

参考链接:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html

你可能感兴趣的:(OkHttpClient详解)