1.新建请求工厂:
RestTemplate 默认有两种工厂对象实现方式,都是 ClientHttpRequestFactory 的子类。如下:
1)SimpleClientHttpRequestFactory 底层使用 java.net.HttpUrlConnection,可配置证书。
2)HttpComponentsClientHttpRequestFactory 底层使用Apache HttpClient访问远程的Http服务,使用HttpClient同样可以配置连接池和证书等信息,而且功能更强大,配置项更多。
这里使用的是SimpleClientHttpRequestFactory工厂对象:
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10*1000);
requestFactory.setReadTimeout(10*1000);
requestFactory.setBufferRequestBody(false);
2.创建Spring提供的Http请求客户端RestTemplate对象用于发送请求:
RestTemplate client = new RestTemplate(requestFactory);
3.创建HTTP请求头:
public void setContentType(@Nullable MediaType mediaType) 设置请求正文(body)的媒体类型,MediaType决定浏览器将以什么形式、什么编码对资源进行解析
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
4.创建HTTP请求实体HttpEntity:
org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity(JSONObject.toJSON("{a:1,b:2}"), headers);
5.用RestTemplate的exchange()方法发送请求, 并用 ResponseEntity 接收响应主体(ResponseBody)的内容:
ResponseEntity httpres = client.exchange(URL.toString(), HttpMethod.POST, requestEntity, String.class);
完整请求过程:
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.lang.Exception;
import java.util.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Controller
@RestController
@RequestMapping("/api/AFS_ORDER")
public class AFS_OrderController extends BaseController {
@GetMapping("/sendInfo")
@ResponseBody
public Object sendInfo(@RequestParam(value="isBatch",required = false,defaultValue = "否")String isBatch,@RequestParam(value="objectId",required = false)String objectId) throws Exception {
try {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10*1000);
requestFactory.setReadTimeout(10*1000);
requestFactory.setBufferRequestBody(false);
RestTemplate client = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
HttpEntity requestEntity = new HttpEntity(JSONObject.toJSON("{a:1,b:2}"), headers);
ResponseEntity httpres = client.exchange(URL.toString(), HttpMethod.POST, requestEntity, String.class);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
?
|