簡體   English   中英

將 ruby​​ 中的 HTTP post 轉換為 java 或 groovy

[英]Convert HTTP post from ruby into java or groovy

我有一些用於訪問 API 的 ruby​​ http post 代碼,但現在我需要將其轉換為 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.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"

並且無法繼續檢查下一個功能,誰能幫我完成java或groovy的http post

您可以使用這里提到的解決方案。 根據此解決方案,您可以實現一個方法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 之前調用doTrustToCertificates() ,如下所示:

    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 trustStore 或者如果您只想信任對於這段代碼,創建一個新的trustStore並指示java使用這個trustStore。

:關於如何使用trsutStore信息可以像在Oracle文檔的幾個位置找到https://docs.oracle.com/cd/E19509-01/820-3503/6nf1il6er/index.htmlhttps://開頭的文檔。 oracle.com/cd/E19830-01/819-4712/ablqw/index.html

基本上,您通過創建 trustStore

keytool -import -file theCertificateToBeTrusted.cert -alias justSomeAlias -keystore myTrustStore

並且您通過使用一些額外參數啟動它來構建 java 以使用此 keyStore

-Djavax.net.ssl.trustStore=/path/toYour/myTrustStore

(我認為您不需要為此用例在 trustStore 上設置密碼)

也看看這個SO答案: 在java程序中使用瀏覽器的證書

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM