package com.example.helloandroid;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
//import org.apache.http.util.EntityUtils;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.yahoo.com");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
//String str = EntityUtils.toString(rp.getEntity());
InputStream is = rp.getEntity().getContent();
String str = is.toString();
TextView tv = new TextView(this);
tv.setText(str);
setContentView(tv);
}
else
{
System.out.println("halo,baby.");
}
}catch(IOException e){
return;
}
}
}
以上是我的代码 但似乎这里有一些问题 那么,任何人都可以给我一些想法吗? 谢谢。
Carmen Lau
答案 0 :(得分:1)
在不知道问题是什么的情况下很难诊断,但我怀疑以下行不是你想要的:
String str = is.toString();
Object.toString()
返回“包含此对象的简洁,人类可读描述的字符串。”这并不总是你所期望的。您可能实际上想要手动提取数据,例如:
byte[] readBytes; // create an empty byte array
is.read(readBytes); // read from the InputStream and put input in the byte array
String str = new String(readBytes); // creat a new String from the byte array
然后将TextView
上的文字设置为str
,就像您现在一样。
答案 1 :(得分:1)
您可以访问此网站。 有一篇关于来自android应用程序的http请求响应的文章。
http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
答案 2 :(得分:0)
对于mldj和MattC, 问题是我无法打印出响应消息。 作为我的编码,导入部分也会发布,但我不知道为什么它们只在编码开始时变成黑色字母。
实际上,我想向雅虎发送一个获取请求并获取回复并将其打印出来。 但现在我打开我的应用程序,它是空白的。
所以,我不确定问题是什么 (1)我用错误的方法打印出来 要么 (2)我的应用无法向雅虎发送请求,并且从一开始到现在都没有收到任何回复。
对于fiXedd, 我今晚会尝试你建议的代码。我认为如果我真的使用错误的方法来打印响应消息,它可以解决问题。非常感谢你。