java直接调用http请求的几种方法

 

1.使用apache HttpClient发送Http请求

首先需要添加依赖:

    <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
以上是我使用的springboot版本,如果项目的父pom也是使用的springboot,那么以下依赖不需要指定版本,版本由springboot指定就可以了


<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <!--<version>4.5.13</version>--> 版本springboot指定
</dependency>

以下是使用一个调用发送邮件的接口来做测试()

@Transactional(rollbackFor = Exception.class)
	public String endTask() {
        
        String url = "xxx.cn";//某接口url
		String to = "xxx@qq.com, xxxxx@qq.com, xxxxx@qq.com";
        String sender = xxxxxds@qq.com;
		String respCtn = "";
		// 1、创建 client 实例
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 2、创建 post 实例
		HttpPost post = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("content", "测试邮件的内容");
		params.add(new BasicNameValuePair("subject", "Exception Email"));//标题没有编码设置,所以最好设置英文,不然乱码
		params.add(new BasicNameValuePair("to", to));
		params.add(new BasicNameValuePair("sender", sender));
		post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

		HttpResponse response = null;
		try {
			if (params != null)
				// 3、设置 post 参数
				post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			// 4、发送请求
			response = httpclient.execute(post);
			respCtn = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			log.error("Fail to connect to remote host [" + url + "]" + e);
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (Exception e) {
				}
			}
		}
		return respCtn;
	}

 2.使用RestTemplate发送Http请求

需要在springboot启动类同路径下生成RestTemplateConfig 类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

以下是调用代码:

@Autowired
private RestTemplate restTemplate;     


public String xxx() {
    RestTemplate restTemplate2 = new RestTemplate();
     String url = "http://127.0.0.1:8080/xxx";
       
        // 封装参数,这里是HashMap
	Map<String, Object> paramMap = new HashMap<String, Object>();
	paramMap.put("变量1", "xxx");
	paramMap.put("变量2", "xxx");

	//1、使用getForObject请求接口
	String result1 = template.getForObject(url, String.class, paramMap);
	System.out.println("result1====================" + result1);

	//2、使用exchange请求接口
	HttpHeaders headers = new HttpHeaders();
	headers.set("id", "lidy");
	HttpEntity<MultiValueMap<String, Object>> httpEntity = new         HttpEntity<MultiValueMap<String, Object>>(null,headers);
	ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
	System.out.println("result2====================" + response2.getBody());
}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事不堪回首..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值