java RestTemplate

01.用法:发送http请求
02.主要的设置参数:
第一.方法类型:

第二.url:

第三.http协议请求头:

java RestTemplate_第1张图片

请求头部
请求头部由关键字/值对组成,每行一对

User-Agent : 产生请求的浏览器类型
Accept : 客户端希望接受的数据类型,比如 Accept:text/xml(application/json)表示希望接受到的是xml(json)类型
Content-Type:发送端发送的实体数据的数据类型。
比如,Content-Type:text/html(application/json)表示发送的是html类型。
Host : 请求的主机名,允许多个域名同处一个IP地址,即虚拟主机

Content-Type详细介绍:
java RestTemplate_第2张图片

关于RestTemplate:

这里RestTemplate类用一个RequestCallback 接口,用lamda表达式实例化。设置自定义的请求

RequestCallback requestCallback = clientHttpRequest -> {
                            clientHttpRequest.getHeaders().set(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3785.3w0. Safari/537.36");
                            clientHttpRequest.getHeaders().set(HttpHeaders.ACCEPT, "*/*");
                            clientHttpRequest.getHeaders().set(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate");
                            clientHttpRequest.getHeaders().set(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9");
                            clientHttpRequest.getHeaders().set(HttpHeaders.CONNECTION, "keep-alive");
                            clientHttpRequest.getHeaders().set(HttpHeaders.HOST, host);
                            clientHttpRequest.getHeaders().set(HttpHeaders.REFERER, referer);
                            clientHttpRequest.getHeaders().set(HttpHeaders.CONTENT_TYPE, "text/plain");
                            clientHttpRequest.getHeaders().set(HttpHeaders.COOKIE, cookie);
                            clientHttpRequest.getHeaders().set("Authorization", token);
                           /* clientHttpRequest.getHeaders().set("orgcodes", orgcodes);
                            clientHttpRequest.getHeaders().set("orgcode1s", orgcode1s);*/
//                            clientHttpRequest.getHeaders().set("params[startOffDate]", startDate);
//                            clientHttpRequest.getHeaders().set("params[endOffDate]", endDate);
//                            clientHttpRequest.getHeaders().set("pageSize", "50000");
//                            clientHttpRequest.getHeaders().set("pageNum", "1");
//                            clientHttpRequest.getHeaders().set("isAsc", "asc");
                        };

RequestCallback :

import java.io.IOException;
import org.springframework.http.client.ClientHttpRequest;

public interface RequestCallback {
    void doWithRequest(ClientHttpRequest var1) throws IOException;
}

public interface ClientHttpRequest extends HttpRequest, HttpOutputMessage {
    ClientHttpResponse execute() throws IOException;
}

响应后服务器发送的的数据接受的java类:
ResponseEntity

它是Spring提供的一个类,它内部封装了状态码,请求头,请求体等信息,可以根据自己的需要去设置状态码、请求体的信息。ResponseEntity中的泛型用于指定请求体的类型,并且ResponseEntity的优先级要高于@ResponseBody,如果返回值是ResponseEntity,即使存在ResponseBody或者@RestController注解,也默认不会生效,而是使用ResponseEntity

public class ResponseEntity<T> extends HttpEntity<T> {
    private final Object statusCode;

    public ResponseEntity(HttpStatus status) {
        this((Object)null, (MultiValueMap)null, (HttpStatus)status);
    }

    public ResponseEntity(T body, HttpStatus status) {
        this(body, (MultiValueMap)null, (HttpStatus)status);
    }

    public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
        this((Object)null, headers, (HttpStatus)status);
    }
    }

这里用的是ResponseExtractor接口来处理响应数据:

 ResponseExtractor<ResponseEntity<String>> responseExtractor = new ResponseExtractor<ResponseEntity<String>>() {
                            @Override
                            public ResponseEntity<String> extractData(ClientHttpResponse clientHttpResponse) throws IOException {
                                try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientHttpResponse.getBody(), "utf-8"))) {
                                    StringBuilder stringBuilder = new StringBuilder();
                                    String line;
                                    while ((line = reader.readLine()) != null) {
                                        stringBuilder.append(line);
                                    }
                                    HttpHeaders headers = clientHttpResponse.getHeaders();
                                    HttpStatus status = clientHttpResponse.getStatusCode();
                                    return new ResponseEntity<>(stringBuilder.toString(), headers, status);
                                }
                            }
                        };

ResponseExtractor接口:

import java.io.IOException;
import org.springframework.http.client.ClientHttpResponse;

public interface ResponseExtractor<T> {
    T extractData(ClientHttpResponse var1) throws IOException;
}

RestTemplate.execute方法:

    ResponseEntity<String> response = restTemplate.execute(monitorDataUrl, HttpMethod.POST, requestCallback, responseExtractor);
                        String respText = response.getBody();
                        //去除特殊字符
                        String cleanedJsonString = respText.replace("\r", "").replace("\n", "");
                        JSONObject jsonObject = JSONObject.parseObject(cleanedJsonString);
                        if (!StringUtils.isEmpty(respText) && Integer.parseInt(jsonObject.getString("total")) > 0) {
                            try {
                                File file = new File(downloadPath + "\\" + Calendar.getInstance().getTimeInMillis() + ".json");
                                if (!file.exists()) file.createNewFile();
                                FileUtils.write(file, respText, "utf-8");
                                quitChrome(webDriver);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }

你可能感兴趣的:(java,开发语言)