将HTTP post从ruby转换为java或groovy

将HTTP post从ruby转换为java或groovy,java,ruby,http,ssl,groovy,Java,Ruby,Http,Ssl,Groovy,我有一些RubyHTTPPOST的代码,用于访问API,但现在我需要将其转换为java或groovy 这是我在ruby上的代码 def loginWithEmailPassword(str_email, str_password) uri = URI(url) req = Net::HTTP::Post.new(uri) req['Content-Type'] = 'application/json' req['x-request-id'] = "xyz-#{SecureRan

我有一些RubyHTTPPOST的代码,用于访问API,但现在我需要将其转换为java或groovy

这是我在ruby上的代码

def loginWithEmailPassword(str_email, str_password)
  uri = URI(url)

  req = Net::HTTP::Post.new(uri)
  req['Content-Type'] = 'application/json'
  req['x-request-id'] = "xyz-#{SecureRandom.hex}"
  req['user-agent'] = 'xyz'

  req.body = { 
  email: str_email, 
  password: str_password
  }.to_json

  Net::HTTP.start(uri.host, uri.port,
    :use_ssl => uri.scheme == 'https',
    :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
    response = http.request(req) # Net::HTTPResponse object

    if(response.code != '200')
      puts response.body # Show response body
      raise ("ERROR: login error... error code #{response.code}")
    end
    return response.body
  end
end
这是我在java上的代码

    def loginApiWithEmailPassword(String sEmail, String sPassword){
            URL url = new URL(m_url + "/login/password");
            JSONObject json = new JSONObject();
            json.put("email", sEmail);
            json.put("password", sPassword);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// set header
            conn.setRequestMethod("POST")
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", aaa);
            conn.setRequestProperty("x-request-id", getSecureRandom(s))
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStream os = conn.getOutputStream();

            os.write(json.toJSONString().getBytes());
            os.close();

            // read the response
            InputStream input = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(input, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            input.close();
            conn.disconnect();

            return jsonObject;
        }
我尝试将其转换为java,但失败了,错误为“javax.net.ssl.SSLHandshakeException:sun.security.validator.validator异常:PKIX路径生成失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径”


由于无法继续检查下一个函数,请任何人帮助我完成http post for java或groovy

您可以使用上面提到的解决方案。根据此解决方案,您可以实现一个方法
doTrustToCertificates()
,然后在设置连接之前调用此方法:

public void doTrustToCertificates() throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
在尝试连接到URL之前,请调用
dotrustocertificates()
,如下所示:

    public void loginApiWithEmailPassword(String sEmail, String sPassword){
            URL url = new URL(m_url + "/login/password");
            JSONObject json = new JSONObject();
            json.put("email", sEmail);
            json.put("password", sPassword);
            doTrustToCertificates();/
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// set header
            conn.setRequestMethod("POST")
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", aaa);
            conn.setRequestProperty("x-request-id", getSecureRandom(s))
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStream os = conn.getOutputStream();

            os.write(json.toJSONString().getBytes());
            os.close();

            // read the response
            InputStream input = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(input, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            input.close();
            conn.disconnect();

            return jsonObject;
        }

因此,您的主要问题是Java不信任您的现成证书。 Yug Singh提到的更换TrustManager的解决方案如果做得好的话应该会起作用,但它不是很干净

更好的解决方案是获取您想要信任的证书(通常您可以通过单击URL中的小锁符号通过浏览器下载),并将其添加到机器的java信任库中,或者如果您只想信任它来获取这段代码,则创建一个新的信任库并指示java使用此信任库

有关如何使用trsutStore的信息可以在多个位置找到,如oracle文档:和

基本上,您可以通过

keytool -import -file theCertificateToBeTrusted.cert -alias justSomeAlias -keystore myTrustStore
通过使用一些额外的参数来启动密钥库,可以引导java使用这个密钥库

-Djavax.net.ssl.trustStore=/path/toYour/myTrustStore
(我认为您不需要为此用例在信任库上设置密码)


还可以看看这个SO答案:

您好,谢谢您的回答,我已经尝试了您的代码,但我遇到了一个错误“失败,因为org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法强制转换对象'blablablabla.RestApi$2@c7a977f将“blabla.RestApi$2”类添加到“oracle.net.jndi.TrustManager”类,有什么线索吗?