【发布时间】:2018-06-09 12:54:08
【问题描述】:
我正在尝试在 Android Studio 中发出 GET 请求,但我不明白为什么此方法在 Eclipse 中作为 Java 程序有效,但在 Android Studio 中无效,所以我认为它与威胁有关,所以我做了对异步任务的调用。
我的代码如下所示:
调用方法:
private static class GetFarmaciasTask extends AsyncTask<String,String,String[][]>{
protected String[][] doInBackground(String... urls) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://mikelmoli.000webhostapp.com/PHP/json.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
JSONObject jsonO = new JSONObject(result.toString());
//JSONObject myResponse = jsonO.getJSONObject("data");
JSONArray tsmResponse = (JSONArray) jsonO.get("data");
String[] indices = {"Nombre", "Provincia", "Poblacion", "Calle", "Numero", "Telefono"};
String[][] datos = new String[tsmResponse.length()][indices.length];
for (int i = 0; i < tsmResponse.length(); i++) {
for (int j = 0; j < indices.length; j++) {
datos[i][j] = tsmResponse.getJSONObject(i).getString(indices[j]);
}
}
return datos;
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException ej) {
ej.printStackTrace();
}
return null;
}
}
错误在这行代码中:
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
正如我之前所说,这个方法在 Eclipse 中作为一个独立的方法工作。
一些让我想到线程错误的错误:
android.os.NetworkOnMainThreadException
引起:android.os.NetworkOnMainThreadException
【问题讨论】:
-
附带说明,如果您的 GET 请求是 REST,请查看使用改造库,因为它处理后台网络请求和对模型的 JSON 解析。
标签: java android http android-asynctask