我试图从一个看起来像这样的URL解析Android 4.4中非常简单的JSON:
{
"code":"asdfg"
}
我有一个适用于Android 7.0的工作代码,但由于某种原因它在Android 4.4中无法运行,而且我在网上使用指南时没有任何运气。
感谢任何帮助:)
编辑 - 当前代码(适用于Android 7但不适用于Android 4.4):
static class Page {
String code;
}
public static String checkIp() throws Exception {
String json = readUrl("https://link.com/json.php"); //Not the real URL, replaced as an example
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
Log.d("MainActivity", page.code);
return (page.code);
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
它在这些方面给我一个错误:
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
错误:
javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8ca3c40: I/O error during system call, Connection reset by peer
W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
W/System.err: at com.android.okhttp.Connection.upgradeToTls(Connection.java:146)
W/System.err: at com.android.okhttp.Connection.connect(Connection.java:107)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
W/System.err: at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
W/System.err: at java.net.URL.openStream(URL.java:470)
答案 0 :(得分:0)
首先,检查网址是否正常工作。有时它会发生链接不起作用。并正确检查 HTTPS或HTTP,因为调用http链接的https(反之亦然)可能会引发此错误。因为握手问题主要出现。
调用方法" checkIp()"需要来自后台线程作为。
new Thread(new Runnable() {
@Override
public void run() {
try {
String s = checkIp();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
除了" thread"之外,代码没有任何问题。问题
我认为这可以解决您的问题。我检查一下它是否正常工作。
如果没有其他工作,请告诉我。
答案 1 :(得分:0)
目标主机没有正确的签名证书。将主机证书添加到您的设备或从GoDaddy等发布机构获取适当的证书或切换到http以进行测试