我已经阅读了很多教学内容,并且努力尝试但不知何故,仍然无法让我的InputStream正常工作。所以我转向你。预先感谢您的帮助!
我的目标是从空白HTML网页获取数据并将其显示在我的Android应用中的TextView上。我在清单中包含了所有互联网权限,而我的XML文件只是线性布局中的文本视图。该应用程序只有一个名为" scorereader"那是关于它的。当我运行它时,它只显示带有textview的空白XML。它不显示来自HttpClient的文本。
JAVA:scorereader.java
public class scorereader extends Activity {
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
TextView tv = (TextView)findViewById(R.id.resultbox);
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://greentapcore.tumblr.com/");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
tv.setText(reader.readLine());
webs.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in HTTP connection "+e.toString());
}
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
来自Tumblr网站的HTML: - 带有" hi"的完整空白页面在顶部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>scoretrack</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
hi
</body>
</html>
提前非常感谢!非常感谢。
答案 0 :(得分:1)
使用HttpGet
代替HttpPost
。 HttpGet
将执行GET请求而不是POST请求,这应该正确下载网页。
答案 1 :(得分:0)
注意日志中的消息
Error in HTTP connection android.os.NetworkOnMainThreadException
在另一个线程中跟随对服务器的请求
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
tv = (TextView)findViewById(R.id.resultbox);
new Task().execute();
}
class Task extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://greentapcore.tumblr.com/");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
try{
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
String line;
while( (line = reader.readLine()) != null) {
result.append(line);
}
webs.close();
return result.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in HTTP connection "+e.toString());
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null){
tv.setText(s);
}
}
}