我正在尝试将网站的内容转换为字符串。我在这个网站和其他网站上搜索了很长时间以找到一个例子,但没有一个有效。
我从教程视频http://www.youtube.com/watch?v=TxcfhAU2dDg中获取了代码
我添加了权限,3G 正在运行(其他应用程序访问互联网并显示图标)。
我也在一个真实的设备上试过,但没有积极的结果。
我可能只是犯了一个愚蠢的错误。你能帮我找到我的错误吗,拜托。
我的代码是:
package com.example.testfail;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.tv);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
httpStuff.setText("ah?");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
和 GetMethodEx:
package com.example.testfail;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
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;
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("google.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) != null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally {
if(in != null){
try {
in.close();
return data;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
任何帮助表示赞赏!