OkHttp3实践--Get、Post方式调用restful服务

最近在项目中需要调取第三方的http服务,在网上搜索了一下httpclient,发现okhttp3这个工具好像比较好用,但是网上对其使用的总结性文章涉及的应用场景都比较简单,故我就自己对其官方文档介绍和javadoc结合自身实践进行一次总结,便于在后续工作中翻看。

Get请求中的基本概念

HttpUrl

  • Scheme:仅支持”http”和”https”,规定检索资源的机制
  • Host:标识网络资源的服务器,可以是ipv4或ipv6地址,也可以是主机名
  • Port:用于连接到web服务器的端口,未指定时使用默认端口(http 80,https 443)
  • Path:路径标识主机上的指定资源,其由segment组成
  • Query:可选,可为null、空或非空;形如url中“?param1Name = param1Value¶m2Name = param2Value”
  • Fragment:不会发送到服务器端,客户端私有;形如url中”#fragment”

实际调用样例

客户端HttpClient

package dist.dgp.util;

import okhttp3.*;

import java.io.IOException;

/**
 * @author yanzy
 * @description okHttpClient封装
 * @date 2018-03-19 14:46
 * @created by intelliJ IDEA
 */
public class HttpClient {
    public static final MediaType type = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
    public static final OkHttpClient httpClient = new OkHttpClient();
    //Get方法调用服务
    public static String httpGet(HttpUrl url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();// 返回的是string 类型
    }
    //Post方法调用服务
    public static String httpPost(HttpUrl url,String content) throws IOException{
        RequestBody requestBody = RequestBody.create(type,content);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }
}

使用客户端发起参数绑定在路径中的Get请求

 @RequestMapping(value = "test/{loginName}",method =  {RequestMethod.GET})
    @ApiOperation(value = "test",notes = "测试服务")
    @ResponseBody
    public String getUser(@PathVariable String loginName) throws IOException {
        /*拼装访问目标url,下面拼装结果为:http://192.168.1.158:8080/dgpFJ-server-web/rest/users/v1/loginname/fjadmin(此值为输入的参数loginName)*/
        HttpUrl url = new HttpUrl.Builder()
                .scheme("http")
                .host("192.168.1.158")
                .port(8080)
                .addPathSegments("dgpFJ-server-web\\rest\\users\\v1\\loginname")
                .addPathSegment(loginName)
                .build();
        System.out.print(url.toString());
        return HttpClient.httpGet(url);
    }

使用客户端发起参数为query的请求

 public Object invokeEntry(int systemID, int dishesID, String data) throws IOException {
        HttpUrl url = HttpUrl.parse(administrativeCentreServicesEntry);
        url.newBuilder()
                /*  下面方法可为HttpUrl添加query部分内容,添加结果为:../../..?systemID = 系统id值&dishesID = 接口编号&data = 参数数据  */
                .addQueryParameter("systemID", String.valueOf(systemID))
                .addQueryParameter("dishesID",String.valueOf(dishesID))
                .addQueryParameter("data",data)
                .build();
        return HttpClient.httpGet(url);
    }

你可能感兴趣的:(OkHttp3实践--Get、Post方式调用restful服务)