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&param2Name = 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);
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用Java原生的HttpURLConnection或者第三方库如Apache HttpClient、OkHttp等来进行HTTP调用。下面分别介绍如何通过GET方法和POST方法调用RESTful API。 GET方法调用: ```java public static String sendGet(String url) { HttpURLConnection connection = null; try { URL getUrl = new URL(url); connection = (HttpURLConnection) getUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } ``` POST方法调用: ```java public static String sendPost(String url, String param) { HttpURLConnection connection = null; try { URL postUrl = new URL(url); connection = (HttpURLConnection) postUrl.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.connect(); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(param); writer.flush(); writer.close(); if (connection.getResponseCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } ``` 以上是通过Java原生的HttpURLConnection来进行HTTP调用的示例,使用第三方库调用方式也类似。需要注意的是,在Spring Boot中可以使用RestTemplate来进行HTTP调用,它是Spring提供的用于简化HTTP访问的模板类,使用起来更加方便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值