当运行代码在控制台中给出这个错误。我使用 Web 服务从服务器的 json api 获取数据。
什么原因?
10-16 13:17:33.389: E/log_tag(651): Error in http connection android.os.NetworkOnMainThreadException
10-16 13:17:33.389: E/log_tag(651): Error converting result java.lang.NullPointerException
10-16 13:17:33.399: E/log_tag(651): Error parsing data org.json.JSONException: End of input at character 0 of
运行此类时发生错误
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
String error_text="";
JSONObject j = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
HttpParams myParams = null;
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//System.out.println("Result = " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
//jArray = new JSONObject(result);
response_status = j.getString("response_status").toString().trim();
if (response_status.equals("0")) {
String getcustomer_id = j.getString("customer_id").toString().trim();
String getPassword = j.getString("password").toString()
.trim();
passData(getcustomer_id, getPassword);
} else {
String getcustomer_id = j.getString("response_status").toString()
.trim();
String getPassword = j.getString("error_text").toString()
.trim();
passData(getcustomer_id, getPassword);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return j;
}
private static void passData(String getcustomer_id, String getPassword) {
id = getcustomer_id;
password = getPassword;
}