java http 外部接口_Java 访问 http 外部接口

Java 访问 http 外部接口

Java 访问 http 外部接口

由于需求需要在后台访问 其他外部接口 所以写了个方法

首先添加maven依赖

org.apache.httpcomponents

httpclient

4.5.5

Service

import org.springframework.http.HttpMethod;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;

import org.springframework.web.client.RestTemplate;

/**

* @author 作者 : 小布

* @version 创建时间 : 2019年6月5日 下午3:42:49

* @explain 类说明 :

*/

@Service

public class HttpService {

public String httpRequest(String url,HttpMethod method){

RestTemplate template = new RestTemplate();

ResponseEntity response = template.getForEntity(url, String.class);

return response.getBody();

}

}

Controller

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpMethod;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

/**

* @author 作者 : 小布

* @version 创建时间 : 2019年6月5日 下午3:42:29

* @explain 类说明 :

*/

@CrossOrigin(origins = "*", maxAge = 3600)

@RestController

@Api(tags = "外部相关接口")

@RequestMapping("/http")

public class HttpController {

@Autowired

private HttpService httpService;

@PostMapping("/httpRequestTest")

@ApiOperation(value="测试外部接口")

public String httpRequestTest(@RequestBody Map map){

return httpService.httpRequest((String)map.get("url"), HttpMethod.GET);

}

}

测试结果

134b640324bec934dea44c979e058818.png

bb269c6c7088b3e69356e71c88c4c261.png

Java 访问 http 外部接口相关教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值