【发布时间】:2014-01-04 22:11:06
【问题描述】:
我正在尝试通过手机调用 REST Web 服务。我正在使用以下代码来完成此操作。我只有一个具有按钮和文本视图的活动。每当我单击按钮时,它都会在logcat 中出现以下错误:
AndroidRuntime :: at android.os.Handler.dispatchMessage(Handler.java:92)
我做错了什么?我该如何解决? 以下是我的课程。
rest.java
public class Rest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_rest);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://192.168.1.145/tst.php";
RestService re = new RestService();
JSONObject jb = RestService.doGet(url);
TextView tv = (TextView) findViewById(R.id.txtView);
tv.setText(jb.toString());
}
});
}
}
RestService.java
public class RestService {
public static JSONObject doGet(String url) {
JSONObject json = null;
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Accept JSON
httpget.addHeader("accept", "application/json");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Get the response entity
// Log.e("myApp", "Issue is here...!");
HttpEntity entity = response.getEntity();
// If response entity is not null
if (entity != null) {
// get entity contents and convert it to string
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// construct a JSON object with result
json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the json
return json;
}
private static String convertStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
【问题讨论】:
-
这就是我在 logcat 中得到的全部内容。
-
你确定吗?也许您已将过滤器应用于 logcat,因此隐藏了其他日志?
-
NetworkOnMainThreadException???真的??? -
@Lukasz'Severiaan'Grela :是的,我已经检查过了,这就是我在 logcat 中得到的全部内容。没有别的。
-
我认为 A.S.意思是在 UI 线程上你正在调用网络操作,这将有效地锁定应用程序直到进程完成,这种任务应该在后台线程中使用例如AsyncTask.
标签: android web-services rest