gpt4 book ai didi

android - Https 帖子在 Android 模拟器上工作但在设备上不工作

转载 作者:太空狗 更新时间:2023-10-29 15:19:16 25 4
gpt4 key购买 nike

我正在尝试使用以下代码将数据发布到 Https URL。我已经入住模拟器工作正常。但它不适用于设备。能有人请帮帮我。

  public Boolean PostData(String data) throws IOException {
Boolean response = false;
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}};

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());

HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}


HostnameVerifier hostnameVerifier =
org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;


SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));

// Set verifier
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append("data").append("=").append(data);
byte[] postData = postDataBuilder.toString().getBytes("UTF-8");

URL postURL = new URL(url);

HttpsURLConnection conn = (HttpsURLConnection) postURL.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));

// ------------------
OutputStream out = conn.getOutputStream();
// --------------------------
out.write(postData);
out.close();

return response;
}

private static class CustomizedHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

在我们之后,有什么方法可以让响应显示在那个 URL 上吗?发布数据。

谢谢,马赫什

最佳答案

您是否使用过 INTERNET 权限?

你必须添加到你的 list 文件:

<uses-permission android:name="android.permission.INTERNET" /> 

(互联网在模拟器上工作正常,但如果你想在真实设备上使用它,你必须使用权限)

关于android - Https 帖子在 Android 模拟器上工作但在设备上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9580353/

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