java发送get和post请求挑过ssh效验

不想改代码,更换java1.8版本解决

package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.pojo.Admin;
import com.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/{id}")
    public List<Admin> findById(@PathVariable Long id) throws Exception {
        return adminService.index();
    }

    public static void main(String[] args) throws Exception {
        try{
            RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
            // 创建请求头
            HttpHeaders headers = new HttpHeaders();
            // 地址
            String url = "https://***/workcheck/SyncWorkCheckApp/dadess?token=asdasjkdadjasnjdkansjnasnd55dadada";
            URI uri = URI.create(url);
            headers.setContentType(MediaType.APPLICATION_JSON);

            //post请求
            JSONObject map = new JSONObject();
            map.put("入参1", "value");
            map.put("入参2", "value");
            org.springframework.http.HttpEntity<JSONObject> entity = new org.springframework.http.HttpEntity<JSONObject>(map, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, entity, JSONObject.class);
            // 返回值
            JSONObject body = responseEntity.getBody();
            // 状态码
            org.springframework.http.HttpStatus statusCode = responseEntity.getStatusCode();
            if ("200".equals(statusCode.toString())) {
                System.out.println("调用成功了!");
            }
            System.out.print(body);
            System.out.print("\n");

            //get请求
            ResponseEntity<JSONObject> responseEntity2 = restTemplate.getForEntity(uri, JSONObject.class);
            JSONObject getbody = responseEntity2.getBody();
            System.out.print(getbody);

            //return body;
        }catch(Exception e){
            e.printStackTrace();
            //return null;
        }
    }
    
}

//跳过SSL认证
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 InterfaceDemo.HttpsClientRequestFactory.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 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", "TLSv1.1", "TLSv1.2"});
            return socket;
        }
    }
}


不跳过效验

package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController{

    @Autowired
    private UserService userService;

    @GetMapping("All/{id}")
    public List<User> findById(@PathVariable Long id) throws InterruptedException, IOException {
        List<User> bb = userService.dade();
        return bb;
    }

    /**
    * 多条件查询
    * */
    @GetMapping("user/{id}")
    public List<User> oneUsel(@PathVariable Long id){
        return userService.oneUser(id);
    }

    @GetMapping("page/{page}/{size}")
    public Page<User> pageUsel(@RequestParam Map searchMap, @PathVariable int page, @PathVariable int size){
        Page<User> dade = userService.pageUser(page, size);
        System.out.print(searchMap);
        System.out.print(searchMap.get("dades"));
        return dade;
    }

    @PostMapping("post/{page}/{size}")
    public String postUser(@RequestBody Map searchMap,@PathVariable int page, @PathVariable int size){
        System.out.print(page);
        System.out.print(size);
        System.out.print(searchMap);
        return "33";
    }

    public static void main(String[] args) {
        try{
            RestTemplate restTemplate = new RestTemplate();
            // 创建请求头
            // 地址
            String url = "https://****:9001/workcheck/SyncWorkCheckApp/getEkaoQin?token=asdasjkdadjasnjdkansjnasnd55dadada";
            URI uri = URI.create(url);
            //get请求
            ResponseEntity<JSONObject> responseEntity2 = restTemplate.getForEntity(uri, JSONObject.class);
            JSONObject getbody = responseEntity2.getBody();
            System.out.print(getbody);


            //post请求
            HttpHeaders headers = new HttpHeaders();
            JSONObject map = new JSONObject();
            map.put("入参1", "value");
            map.put("入参2", "value");
            org.springframework.http.HttpEntity<JSONObject> entity = new org.springframework.http.HttpEntity<JSONObject>(map, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, entity, JSONObject.class);
            // 返回值
            JSONObject body = responseEntity.getBody();
            System.out.print(body);
            //return body;
        }catch(Exception e){
            e.printStackTrace();
            //return null;
        }
    }



}

最简单的眺过ssl

package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.pojo.Admin;
import com.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/{id}")
    public List<Admin> findById(@PathVariable Long id) throws Exception {
        return adminService.index();
    }

    static class miTM implements TrustManager,X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }
        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException {
        //眺过ssl效验
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new AdminController.miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        try{
            RestTemplate restTemplate = new RestTemplate();
            // 创建请求头
            // 地址
            String url = "https://flow.gdzawy.com:9001/workcheck/SyncWorkCheckApp/getEkaoQin?token=asdasjkdadjasnjdkansjnasnd55dadada";

            URI uri = URI.create(url);
            //get请求
            ResponseEntity<JSONObject> responseEntity2 = restTemplate.getForEntity(uri, JSONObject.class);
            JSONObject getbody = responseEntity2.getBody();
            System.out.print(getbody);


            //post请求
            HttpHeaders headers = new HttpHeaders();
            JSONObject map = new JSONObject();
            map.put("入参1", "value");
            map.put("入参2", "value");
            HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(map, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, entity, JSONObject.class);
            // 返回值
            JSONObject body = responseEntity.getBody();
            System.out.print(body);
            //return body;
        }catch(Exception e){
            e.printStackTrace();
            //return null;
        }
    }


}


  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大得369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值