Atitit webclient httpclient技术总结 RestTemplate
Atitit CateIT重要技术httpclient iduah2 impt
体系树路径:CS IT> net . http ftp
密级和保密期限::
Keywords和摘要:none
目录
2.2. Rest工具 RestTemplate Feign 2
2.3. Netty、Mina 这样的网络 IO 框架过于底层 2
3.1. WebClient(它会自动根据url来识别是FTP还是Http) 3
1. 概念 与组成 2
1.1. Httpentity 2
1.1.1. Fileentity 2
1.1.2. Stringentiry 2
1.1.3. Urlencodeformentity 2
1.2. Method 2
1.2.1. Get post put del 2
在 Java 社区中,HTTP Client 主要有 JDK 的 HttpURLConnection、Apache Commons HttpClient(或被称为 Apache HttpClient 3.x)、Apache HttpComponents Client(或被称为 Apache HttpClient 4.x)、Square 公司开源的 OkHttp。
除了这几个纯粹的 HTTP Client 类库以外,还有 Spring 的 RestTemplate、Square 公司的 Retrofit、Netflix 公司的 Feign,以及像 Apache CXF 中的 client 组件。这些框架和类库主要是针对 Web Service 场景,尤其是 RESTful Web Service。它们往往是基于前面提到的 HTTP Client 实现,并在其基础上提供了消息转换、参数映射等对于 Web Service 来说十分必要的功能。
(当然,像 Netty、Mina 这样的网络 IO 框架,实现 HTTP 自然也不再话下,但这些框架通常过于底层,不会被直接使用)
就是通过创建WebRequest(它会自动根据url来识别是FTP还是Http)来操作的。可以说,与其你费劲去创建HttpWebRequest,再创建WebResponse,最后才读取数据,当然不如直接使用WebClient方便啦!但是这只是方便程度不同,对于你的这个问题没有差别。
* */
public class TransInterceptor extends HandlerInterceptorAdapter {
/**
* 。该方法的返回至是 Boolean 类型,当它返回 false 时,表示请求结束,后续的 Interceptor 和 Controller 都不会再执行;当它返回为 true 时会继续调用下一个 Interceptor 的 preHandle 方法,如果已经是最后一个 Interceptor 的时候就会调用当前请求的 Controller 方法。
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String destUrl = "http://localhost:80"+request.getRequestURI();
long startTime = System.currentTimeMillis();
System.out.println(" --------LogInterception.preHandle---");
if( request.getRequestURI().toLowerCase().startsWith("/actuator"))
return true;
System.out.println("RequestURL:" + request.getRequestURL());
System.out.println("StartTime:" + System.currentTimeMillis());
// response.getWriter().write( "拦截内容lejye neiron from svr proder.. ");
//
// if("1".equals("1"))
// return false;
// System.out.println(json);
// 构造URI。必须拼接出String url然后创建URI,否则会出现queryString %符号转%25的问题
HttpMethod method = getHttpmethod(request);
URI destUri = new URI(destUrl+"?"+ getQueryString(request));
System.out.println(destUri);
HttpEntity<Object> requestEntity = getHttpHearderAndParams(request);
// 向服务请求
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(destUri, method, requestEntity, String.class);
response.getWriter().write( responseEntity.getBody().toString());
// return responseEntity;
// request.setAttribute("startTime", startTime);
return false; //cancel next process
}
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public class RestTemplateUtil {
public static HttpMethod getHttpmethod(HttpServletRequest request) {
HttpMethod method = null;
if (request.getMethod() == HttpMethod.POST.name())
method = HttpMethod.POST;
if (request.getMethod() .equals(HttpMethod.GET.name()) )
method = HttpMethod.GET;
return method;
}
public static String getQueryString(HttpServletRequest request) {
String destUrl = "";
if (request.getQueryString()!=null && !request.getQueryString().isEmpty())
destUrl += "?" + request.getQueryString();
return destUrl;
}
//请求实体
public static HttpEntity<Object> getHttpHearderAndParams(HttpServletRequest request) {
// 根据request,构造HttpHeaders
String body=null;
HttpHeaders headers = new HttpHeaders();
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()){
String name = (String)headerNames.nextElement();
String value = request.getHeader(name);
headers.add(name, value);
}
// 复制 request 的参数
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
// 附加参数值
Set<String> keySet = parameterMap.keySet();
for (String key : keySet) {
String[] value = parameterMap.get(key);
params.add(key, value[0]);
}
// 根据body内容填充requestEntity。对于form-data,body为空但parameterMap有值;对于raw,body不为空。
HttpEntity<Object> requestEntity = (body!=null && !body.isEmpty())? new HttpEntity<>(body, headers): new HttpEntity<>(params, headers);
return requestEntity;
}
}
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class CookieTest {
/**
*
* array(1) {
["aaa"]=>
string(2) "11"
}
* @param args
* @throws URISyntaxException
*/
public static void main(String[] args) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", "aaa=11" );
RestTemplate restTemplate = new RestTemplate();
// URI url= new URI("http://localhost:9088/cktest");
// System.out.println( restTemplate.getForObject(url, String.class));
String url = "http://localhost/showck.php";
url="http://localhost:9088/cktest";
ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET,
new HttpEntity (headers) ,String.class);
System.out.println(response.getBody());
//http://localhost/showck.php
}
}