我正在尝试启动第一个处理Http请求的应用。以下代码来自教程书,但不起作用:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
我的意思是说它不起作用 - 我在手机上运行它并且LogCat显示第一个System.out.println而不是第二个,有错误说: E /(1755):无法打开文件进行阅读
我在这里读了一些关于以异步方式制作它的线程,但如果是这样,那么应用程序会崩溃,而且,这是一本书的例子,所以它应该可以工作,不应该吗?目标手机运行ICS 怎么了? 感谢