gpt4 book ai didi

java - 将 HTTP post 从 ruby​​ 转换为 java 或 groovy

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:25 25 4
gpt4 key购买 nike

我有一些用于访问 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:无法找到请求目标的有效证书路径”

无法继续检查下一个功能,谁能帮我完成java或groovy的http post

最佳答案

您可以使用提到的解决方案 here .根据此解决方案,您可以实现一个方法 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 - 将 HTTP post 从 ruby​​ 转换为 java 或 groovy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52076592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com