使用SpringBoot 实现了HTTP请求(post/get),总结如下
HTTPRequest 请求工具类
package com.aliyun.mq.util;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
public class HttpRestUtils {
/**
* http post
* */
public static String post(String url, MultiValueMap<String, String> params) throws IOException {
return httpRestClient(url, HttpMethod.POST, params);
}
/**
* http get
* */
public static String get(String url, MultiValueMap<String, String> params) throws IOException {
return httpRestClient(url, HttpMethod.POST, params);
}
/**
* HttpMethod post/get
* */
private static String httpRestClient(String url, HttpMethod method, MultiValueMap<String, String> params) throws IOException {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10*1000);
requestFactory.setReadTimeout(10*1000);
RestTemplate client = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
//headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
// 执行HTTP请求
ResponseEntity<String> response = null;
try{
response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
catch (HttpClientErrorException e){
System.out.println( "------------- 出现异常 HttpClientErrorException -------------");
System.out.println(e.getMessage());
System.out.println(e.getStatusText());
System.out.println( "-------------responseBody-------------");
System.out.println( e.getResponseBodyAsString());
e.printStackTrace();
return "";
}
catch (Exception e) {
System.out.println( "------------- HttpRestUtils.httpRestClient() 出现异常 Exception -------------");
System.out.println(e.getMessage());
return "";
}
}
}
工具类使用案例
import com.aliyun.mq.util.HttpRestUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.annotation.Resource;
import java.util.Date;
public String PostData()
{
try{
//api url地址
String url = "http://127.0.0.1:8082/test/respost";
//post请求
HttpMethod method =HttpMethod.POST;
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
params.add("name", "wangru");
params.add("sex", "男");
params.add("age", "27");
params.add("address", "Jinan China");
params.add("time", new Date().toString());
System.out.print("发送数据:"+params.toString());
//发送http请求并返回结果
String result = HttpRestUtils.post(url,params);
System.out.print("接收反馈:"+result);
return result;
}catch (Exception e){
System.out.println( "------------- "+this.getClass().toString()+".PostData() : 出现异常 Exception -------------");
System.out.println(e.getMessage());
return "";
}
}
发送和接收请求
import com.aliyun.mq.service.MqService;
import com.aliyun.mq.util.JsonUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RequestMapping("/test")
@RestController
public class IndexController {
/**
* 响应post请求
* @return
*/
@RequestMapping(value = "/respost", method = RequestMethod.POST)
public String respost(){
return "response post success";
}
/**
* 发出post请求
* @return
*/
@GetMapping("/reqpost")
public String reqpost(){
System.out.println("this.getClass(): " + this.getClass().toString());
String svalue = mqService.PostData();
return svalue;
}
}
遇到的问题总结:
1、405 Method not allowed , Request method 'POST' not supported
解决:在@RequestMapping中Method 没有指定为post。 即要加上 @RequestMapping(value = "/test/respost", method = RequestMethod.POST)
2、出现 Message Not Found
解决: 因为 @RequestMapping(value = "/test/respost", method = RequestMethod.POST) 中的 value 值错误,导致无法找到入口地址,更改为 @RequestMapping(value = "/respost", method = RequestMethod.POST) 就成功