首页 > 解决方案 > 将 HTTP 帖子从 ruby​​ 转换为 java 或 groovy

问题描述

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

这是我在红宝石上的代码

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帖子

标签: javarubyhttpsslgroovy

解决方案


因此,您的主要问题是 Java 不信任您开箱即用的证书。如果操作正确,Yug Singh 提到的更改 TrustManager 的解决方案应该可以工作,但恕我直言,它不是很干净。

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

有关如何使用 trsutStore 的信息可以在多个位置找到,例如 oracle 文档:https ://docs.oracle.com/cd/E19509-01/820-3503/6nf1il6er/index.html和https://docs。 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 答案:Using browser's certificate in java program


推荐阅读