POST:
RestTemplate restTemplate = new RestTemplate();
StringBuffer url= new StringBuffer(LiveGoodsUtils.ADD);
url.append(WeixinInfoUtils.accessToken);
//请求头
HttpHeaders httpHeaders = new HttpHeaders();
//定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON_UTF8
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
//RestTemplate带参传的时候要用HttpEntity>对象传递--请求发起的参数
HttpEntity request = new HttpEntity(obj, headers);
//发送请求
ResponseEntity entity = restTemplate.postForEntity(url.toString(), request, String.class);
//获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
String body = entity.getBody();
System.out.println("body:"+body);
AddResponseVo parseObject = JSON.parseObject(body, AddResponseVo.class);
System.err.println("result:"+parseObject);
GET:
public GetApprovedResponseVo getapproved(GetApprovedRequestVo obj) {
RestTemplate restTemplate = new RestTemplate();
StringBuffer url= new StringBuffer(LiveGoodsUtils.ADD_GOODS);
url.append(WeixinInfoUtils.accessToken);
//定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON_UTF8
HttpHeaders headers = HttpHeadersUtils.getHeadersInstance();
//RestTemplate带参传的时候要用HttpEntity>对象传递
HttpEntity request = new HttpEntity(obj, headers);
//这里指定请求类型,HttpMethod.GET,也可修改参数改成POST
ResponseEntity exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, request, GetApprovedResponseVo.class);
GetApprovedResponseVo body = exchange.getBody();
return body;
}
配置使用HTTPS:
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
* see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
*/
// SSLSocketFactory用于创建 SSLSockets
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
// 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
// 这些默认的服务的最低质量要求保密保护和服务器身份验证
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
// 返回的密码套件可用于SSL连接启用的名字
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port,
final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
final int localPort) throws
IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
return socket;
}
}
}
import org.springframework.web.client.RestTemplate;
public class RestTemplateHttpsFactory {
private volatile static RestTemplate restTemplate;
private RestTemplateHttpsFactory(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public static RestTemplate getRestTemplateInstance(){
if(null==restTemplate){
synchronized (RestTemplateHttpsFactory.class){
if(null==restTemplate){
HttpsClientRequestFactory httpsClientRequestFactory = new HttpsClientRequestFactory();
httpsClientRequestFactory.setConnectTimeout(5000);
httpsClientRequestFactory.setReadTimeout(5000);
restTemplate = new RestTemplate(httpsClientRequestFactory);
}
}
}
return restTemplate;
}
}
发图携带图片请求:
@Override
public UploadResponseVo upload(UploadRequestVo obj) {
StringBuffer httpMethod = new StringBuffer(MediaUploadUtils.url);
httpMethod.append(obj.getAccessToken())
.append("&type=").append(obj.getType());
RestTemplate restTemplate = RestTemplateHttpsFactory.getRestTemplateInstance();
//String args = "";
MultiValueMap paramMap = new LinkedMultiValueMap<>();
/*paramMap.add("args", args);
paramMap.add("sign", "");*/
//File file=new File(filePath);
File file=obj.getFile();
String suffix = file.getName().substring(file.getName().lastIndexOf("."));
String name = UUID.randomUUID().toString().replace("-","");
String fileName = name+suffix;
byte[] bytesArray = new byte[(int) file.length()];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
}catch (Exception e){
e.printStackTrace();
}
ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
@Override
public String getFilename() {
return fileName;
}
};
paramMap.add("media", contentsAsResource);
String result = restTemplate.postForObject(httpMethod.toString(), paramMap, String.class);
System.out.println("post json : " + result);
UploadResponseVo resultObj = JSON.parseObject(result, UploadResponseVo.class);
return resultObj;
}
public static void main(String[] args) {
UploadRequestVo obj = new UploadRequestVo();
obj.setAccessToken(WeixinInfoUtils.accessToken);
obj.setType("image");
File file=new File("D:/img/testUpload.jpg");
obj.setFile(file);
MediaUploadServiceImpl mediaUploadService = new MediaUploadServiceImpl();
mediaUploadService.upload(obj);
}