【发布时间】:2017-11-13 20:37:39
【问题描述】:
我构建了一个从服务器上的 json 获取数据的应用程序。在这一刻,我使用这篇文章下的代码连接到 json 文件。首先它工作得很好,但一段时间后它停止工作,我在显示器或安卓屏幕上看不到错误。我认为是 DataOutputStream,但我看不出问题出在哪里。
有人可以让它工作吗?
public String makeServiceCall(String reqUrl, Context con) {
String response = null;
context = con;
DB = new DatabaseVerwerker(context); //<-- database verbinden
try {
URL url = new URL(reqUrl);
String[] UrlOnderdeel = reqUrl.split("://");
if(UrlOnderdeel[0].equals("http")) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setAllowUserInteraction(false);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
dos.close();
conn.connect();
int responseCode = conn.getResponseCode();
InputStream in = new BufferedInputStream(conn.getInputStream());
if(responseCode >= 300 && responseCode < 400) {
response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
} else {
response = convertStreamToString(in);
}
}
if(UrlOnderdeel[0].equals("https")) {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new TrustAll()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setAllowUserInteraction(false);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
dos.close();
conn.connect();
int responseCode = conn.getResponseCode();
if(responseCode >= 300 && responseCode < 400) {
response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
} else {
response = convertStreamToString(conn.getInputStream());
}
}
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
if(response != null) {
Log.v("JsonRespons", response.toString());
}
return response;
}
【问题讨论】:
-
conn.connect();。陈述毫无意义。在这两种情况下,您已经写入了输出流,没有连接是不可能的。删除两次。 -
dos.close();。如果您必须从另一个流中读取,请不要关闭流。