OkHttp3的用法Demo

maven架包导入



   com.squareup.okhttp3
   okhttp
   3.8.1

java代码

package com.asset.utils;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpRequest {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    public String get(String url) throws IOException {
      Request request = new Request.Builder()
          .url(url)
          .build();

      Response response = client.newCall(request).execute();
      return response.body().string();
    }

public String post(String url, String json) throws IOException {
      RequestBody body = RequestBody.create(JSON, json);
      Request request = new Request.Builder()
          .url(url)
          .post(body)
          .build();
    /*  Call call = client.newCall(request);
      call.*/
      
      Response response = client.newCall(request).execute();
      return response.body().string();
    }   
}

调用请求
代码示例:这是调用访问钉钉的开发开放平台

package com.shengtong.asset.assetdetail;
import java.io.IOException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.CorpMessageCorpconversationAsyncsendRequest;
import com.dingtalk.api.response.CorpMessageCorpconversationAsyncsendResponse;
import com.asset.utils.OkHttpRequest;
import com.taobao.api.ApiException;
/**
 * Title:DingDingExtensionsUtil.java
 * Description:访问钉钉开放接口的工具类
 * @author Wu
 * @date 2018年3月1日 下午2:41:52
 */
public class DingDingExtensionsUtil {
/**
 * 根据corpId,corpSecret调用接口生成accessToken
 * @param corpId
 * @param corpSecret
 * @return
 */
public String getAccessToken(String corpId, String corpSecret) {
    //返回的accessToken:String类型的Json串,需解析Json才能拿到里面的accessToken
    String accessToken = "";
    OkHttpRequest okHttpRequest = new OkHttpRequest();
    //生成accessToken的接口URL
    String accessTokenUrl = "https://oapi.dingtalk.com/gettoken?corpid="+corpId+"&corpsecret="+corpSecret;
    try {
        //发送请求
        accessToken = okHttpRequest.get(accessTokenUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return accessToken;
  }
}

你可能感兴趣的:(OkHttp3的用法Demo)