请求帮助在Android中编写HTTP请求

请求帮助在Android中编写HTTP请求,android,Android,以上是我的代码。 但这里似乎存在一些问题。 那么,任何人都可以给我一些想法吗? 多谢各位 Carmen Lau不知道问题是什么,很难诊断,但我怀疑下面这句话不是你想要的: package com.example.helloandroid; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.os.Bundle; import android.wi

以上是我的代码。
但这里似乎存在一些问题。
那么,任何人都可以给我一些想法吗?
多谢各位


Carmen Lau

不知道问题是什么,很难诊断,但我怀疑下面这句话不是你想要的:

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;
        }
    }
}
Object.toString()
返回“一个包含此对象简明易读描述的字符串”。这并不总是您所期望的。实际上,您可能希望通过以下方式手动提取数据:

String str = is.toString();

然后将
TextView
上的文本设置为
str
,就像您刚才所做的那样。

对于mldj和MattC, 问题是我无法打印响应消息。 作为我的编码,导入部分也会输出,但我不知道为什么它们只有在编码开始时才会变成黑色

实际上,我想向Yahoo发送一个get请求,然后返回响应并打印出来。 但现在我打开我的应用程序,它是空白的

所以,我不确定问题是什么 (1)我使用了错误的方法打印出来 或 (2)我的应用程序无法向雅虎发送请求,从一开始到现在都没有收到任何回复

对于fiXedd,
今晚我将尝试你建议的代码。如果我真的使用错误的方法打印响应消息,我认为这可以解决问题。非常感谢。

您可以访问此网站。 有一篇文章是关于android应用程序的http请求响应的


您面临的问题是什么?错误还是错误的行为?您是否必须使用HttpClient并尝试HttpUrlConnection?是的,您遇到了什么错误?代码在我看来还行,只是简单地看了一下。
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