Java教程

RestTemplate

本文主要是介绍RestTemplate,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

`package io.renren.common.utils;

import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;

/**
*RestTemplate工具类
*
*/
public class RestTemplateUtils {

public static Object getHttpUrlEncodeRequest(String url, Object request) {
    Object result = null;
    //设置代理
    RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
        {
            setProxy(new java.net.Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", Integer.parseInt("8080"))));
        }
    });
    //设置请求头
    HttpHeaders httpHeaders = new HttpHeaders();
    //请求格式,可以设置别的类型urlencoded类型在请求时会自动将请求参数进行urlencode不用事先进行处理。
    httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //设置参数,请求体可以为Sring,json等类型
    MultiValueMap<String,Object> params=new LinkedMultiValueMap<>();
    params.put("id", Collections.singletonList(request));
    HttpEntity<Object> objectHttpEntity = new HttpEntity<>(params, httpHeaders);
    try {
        ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, objectHttpEntity, Object.class);
        result = response.getBody();
        int code = response.getStatusCodeValue();
    } catch (RestClientException e) {
        e.printStackTrace();
    }
    return result;
}

public static Object getHttpJsonRequest(String url, Object request) {
    Object result = null;
    //设置代理
    RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
        {
            setProxy(new java.net.Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", Integer.parseInt("8080"))));
        }
    });
    //设置请求头
    HttpHeaders httpHeaders = new HttpHeaders();
    //请求格式,可以设置别的类型
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    //设置请求体,请求体可以为Sring,json等类型
    HttpEntity<Object> objectHttpEntity = new HttpEntity<>(request, httpHeaders);
    try {
        ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, objectHttpEntity, Object.class);
        result = response.getBody();
        int code = response.getStatusCodeValue();
    } catch (RestClientException e) {
        e.printStackTrace();
    }
    return result;
}

}
`

这篇关于RestTemplate的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!