【问题标题】:Android working HttpRequest Class [closed]Android工作HttpRequest类[关闭]
【发布时间】:2013-03-25 22:17:37
【问题描述】:

我正在寻找一个可以工作的 HtttpRequest Class ,这样我就可以这样做:

String response = Request.get("http://google.com");

我已经写了一个类,但它在 Android 3+ 上不起作用,但在 2.3 上却可以。

public class WebRequest {
public String get(String url){
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);


        return responseBody;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

请帮忙!!!

【问题讨论】:

  • 它在 2.3 中工作吗?如果是,请检查错误是否是严格模式策略,如果是,则将其转移到异步任务
  • 它可能与编码有关,尝试传递一个 utf-8 编码的 url
  • 请显示代码,这不起作用。
  • URL 是 utf-8 编码的。它正在开发 2.3。你能把它转移到异步任务吗?我不知道该怎么做,我可以直接返回响应......

标签: java android


【解决方案1】:

你可以看看这个答案:How do I use the Simple HTTP client in Android?

他们使用这两种方法:

public static void connect(String url) 
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

private static String convertStreamToString(InputStream is)
{

    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

更新

使用 AsyncTask:Android HTTP Request AsyncTask

更新 2 - 简单版

    public class XmlTask extends AsyncTask<String, Void, String>{

    public String doInBackground(String... urls){
        String url = urls[0];

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                // now you have the string representation of the HTML request
                instream.close();
            }

                return xml;
            }
    }

    public void onPostExecute(String xml){
        // Your XML parsing statement here
    }
}

在创建这个类(并创建你自己的 xml 解析器?!)之后,使用以下内容:

String result = new XmlTask().execute("http://google.com");

【讨论】:

  • 我认为你必须在 Android 3+ 上使用 AsyncTask。
  • 也许这就是你要找的@user1849921? Android HTTP Request AsyncTask
  • 是的,但是我如何直接返回我可以在开始执行的地方继续执行的响应?
  • 就像答案中提到的那样:YourClassExtendingJSONTask task = new YourClassExtendingJSONTask(); task.execute(url); 意味着您必须创建另一个类(例如:YourClassExtendingJSONTask.class)并扩展 JSONTask 类。此外,您必须在 YourClassExtendingJSONTask.class 中实现自己的 customMethod(JSONObject json) 方法。
  • 是的,但我需要字符串形式的响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2013-05-10
  • 2016-03-07
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多