http访问接口/调用第三方接口传参、接口端接参记录

一、http访问接口/调用第三方接口工具方式
json工具pom依赖:

<!-- 阿里JSON解析器 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.79</version>
        </dependency>

1.HttpClient
pom依赖

<!-- httpClient工具 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
        </dependency>

1.2 访问示例
1.2.1 get请求

public void httpGet() {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数
        StringBuffer params = new StringBuffer();
        try {
            // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("name=" + URLEncoder.encode("&", "utf-8"));
            params.append("&");
            params.append("age=24");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://******:****/httpGet" + "?" + params);
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

接口端:
@RequestParam 底层是通过request.getParameter方式获得参数的,按理说@RequestParam 和request.getParameter是同源;
@RequestParam、request.getParameter可以处理get 方式中queryString的值,也可以处理post方式中 body data的值。@RequestParam、request.getParameter用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST。

@RequestMapping("/httpGet")
public String httpGet(@RequestParam String name, String age) {
	System.out.println("name接收=" + name);
	System.out.println("age接收=" + age);
	// 业务逻辑
}
@RequestMapping("/httpGet")
public String httpGet(HttpServletRequest request) {
	String name= request.getParameter("name");
	// 业务逻辑
}

1.2.2 post请求
当前端请求的Content-Type是Json时,可以用@RequestBody这个注解来解决;
@RequestBody接受的是一个json对象的字符串,而不是Json对象,在请求时往往都是Json对象,可使Json工具(JSONObject.toJSONString)将对象转换成json字符串。

/**
* 参数集合可以是map、实体类,按理讲json对象也可,因为接口端使用@RequestBody修饰参数,接收的是json字符串格式,
* 前者都可使用工具转换为json字符串格式进行参数传输
*/
public static void sendPost(String url, String data, String sign) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://******:***/httpPost");

		// 设置实体参数
		// User user = new User();
		// user.setName("test");
		// user.setAge(18);
		// String jsonString = JSON.toJSONString(user);
		
        // 设置map参数集合
        HashMap<String, String> param = new HashMap<>();
        param.put("data",data);
        param.put("sign",sign);
        String toJSONString = JSONObject.toJSONString(param);
        StringEntity stringEntity = new StringEntity(toJSONString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(stringEntity);

        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String s = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);// 可手动设置编码,解决响应乱码问题
            JSONObject jsonObject = JSONObject.parseObject(s);
            int code = (Integer) jsonObject.get("code");
            System.out.println("响应码:" + code);
            if (responseEntity != null) {
                System.out.println("响应内容为:" + s);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

接口端:

	// 参数为map集合
	@PostMapping("/httpPost")
    @ResponseBody
    public String httpPost(@RequestBody Map<String,String> param) {
		if(param.size() != 0){
			String name = param.get("data");
		}
	}
	// 参数为实体类
	@PostMapping("/httpPost")
    @ResponseBody
    public String httpPost(@RequestBody User user) {
		String name = user.getName();
	}

2.hutool工具库
pom依赖

<!-- hutool-http工具类 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.11</version>
        </dependency>

2.2 访问示例
2.2.1 get请求

	public String hutoolGet(String url) {
		HashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头
		headers.put("Content-Type","application/x-www-form-urlencoded;charset=utf8"); // 使用默认类型
		// 设置参数集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("data","xxxxxxxxxxxxxxx"); //键名对应实体类vo属性名
        return HttpUtil.createGet(url).addHeaders(headers).form(map).execute().body();
    }

2.2.2 post请求
传参json字符串,两种封装工具请求方法

	public String hutoolPost(String url){
		// 设置参数集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("data","xxxxxxxxxxxxxxx");
        String json = JSONObject.toJSONString(map); // 转为json字符串格式
        return HttpRequest.post(url).header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
                .body(json).execute().body();
        // return HttpUtil.post(url, json);
    }

接口端:

 	@PostMapping("/hutoolPost")
    @ResponseBody
    public String hutoolPost(@RequestBody Map<String,String> json) {
		String data = json.get("data");
	}

传参map
:可用于(原生表单默认类型)Content-Type: application/x-www-form-urlencoded,接口端可使用@RequestParam接参、实体类接参

	public String hutoolPost(String url){
		// 设置参数集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","xxxx");
        return HttpUtil.post(url, map);
    }

接口端:
@RequestParam修饰map接参

	@PostMapping("/hutoolPost")
    @ResponseBody
    public String hutoolPost(@RequestParam Map<String,String> map) {
		String data = map.get("name");
	}

实体类接参,传参集合键名对应实体类属性即可接收成功

	@PostMapping("/hutoolPost")
    @ResponseBody
    public String hutoolPost(User user) {
    	String name = user.getName();
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值