将 HTTP 帖子从 ruby 转换为 java 或 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帖子

您可以使用此处提到的解决方案。根据此解决方案,您可以实现一个方法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.html 和 https://docs.oracle.com/cd/E19830-01/819-4712/ablqw/index.html

基本上,您可以通过以下方式创建信任存储

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

并且您不需要Java通过使用一些额外的参数启动它来使用此密钥库

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

(我认为您不需要为此用例在信任商店上设置密码(

也看看这个SO答案:在java程序中使用浏览器的证书

最新更新