【问题标题】:How to make Sync or Async HTTP Post/Get如何进行同步或异步 HTTP Post/Get
【发布时间】:2015-06-19 11:19:31
【问题描述】:

我需要同步或异步 HTTP Post/Get 从 Web 服务获取 HTML 数据。我搜索了整个互联网,但我无法给出好的结果。

我尝试使用以下示例:

但没有一个对我有用。

HttpClientHttpGet 被划掉,错误是:

“org.apache.http.client.HttpClient 已弃用”

代码:

try
{
    HttpClient client = new DefaultHttpClient();
    String getURL = "google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    if (resEntityGet != null)
    {
        //do something with the response 
    }
}
catch (Exception e)
{
    e.printStackTrace();
}

【问题讨论】:

  • 可能是如果您发布您尝试中的错误可能会导致结果。
  • 我无法运行应用程序,因为 HttpClient 和 HttpGet 被划掉,错误是:“org.apache.http.client.HttpClient 已弃用” 代码:尝试 { HttpClient client = new DefaultHttpClient();字符串 getURL = "google.com"; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //对响应做一些事情 } } catch (Exception e) { e.printStackTrace(); }
  • 你需要找出你跑不了的原因
  • 编译器告诉我这个错误:“org.apache.http.client.HttpClient is deprecated”

标签: android http


【解决方案1】:

我在下面发布的示例基于我在 Android 开发人员文档 上找到的示例。您可以找到该示例 HERE,查看该示例以获得更全面的示例。

您将能够通过以下方式发出任何 http 请求

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new DownloadTask().execute("http://www.google.com/");
    }

    private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //do your request in here so that you don't interrupt the UI thread
            try {
                return downloadContent(params[0]);
            } catch (IOException e) {
                return "Unable to retrieve data. URL may be invalid.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            //Here you are done with the task
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
        }
    }

    private String downloadContent(String myurl) throws IOException {
        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);
            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);
        return new String(buffer);
    }
}

您可以根据自己的需要使用代码

【讨论】:

  • 编译器无法识别:HttpURLConnection、URL、openConnection() 等。见图:postimg.org/image/sjaav97yx
  • 我添加了库但仍然有一些错误,请参阅屏幕:postimg.org/image/re791wksx
  • 我错过了这个:private String downloadContent(String myurl) 抛出 IOException 并且此时错误失修 :):) 谢谢你的帮助,我正在测试我的代码并给你反馈。
  • 很高兴,如果有帮助记得标记为答案。
  • 我已经标记了你的答案。非常感谢尼尔 :) 你节省了我 3 天的工作时间
【解决方案2】:

您可以使用Volley 它为您提供所需的一切。如果您决定使用 AsyncTask 并自己编程,我建议您不要在 Activity 中使用 AsyncTask,而是将其放在包装类中并使用回调。这使您的活动保持清洁并使网络代码可重用。这或多或少是他们在 Volley 中所做的。

【讨论】:

  • 排球是一个很好的选择,实际上是一个更好的选择!
【解决方案3】:
**Async POST & GET request**

public class FetchFromServerTask extends AsyncTask<String, Void, String> {
    private FetchFromServerUser user;
    private int id;

    public FetchFromServerTask(FetchFromServerUser user, int id) {
        this.user = user;
        this.id = id;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        user.onPreFetch();
    }

    @Override
    protected String doInBackground(String... params) {

        URL urlCould;
        HttpURLConnection connection;
        InputStream inputStream = null;
        try {
            String url = params[0];
            urlCould = new URL(url);
            connection = (HttpURLConnection) urlCould.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setRequestMethod("GET");
            connection.connect();

            inputStream = connection.getInputStream();

        } catch (MalformedURLException MEx){

        } catch (IOException IOEx){
            Log.e("Utils", "HTTP failed to fetch data");
            return null;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    protected void onPostExecute(String string) {

        //Do your own implementation
    }
}


****---------------------------------------------------------------***


You can use GET request inn any class like this:
new FetchFromServerTask(this, 0).execute(/*Your url*/);

****---------------------------------------------------------------***

对于 Post 请求,只需更改:connection.setRequestMethod("GET");到

connection.setRequestMethod("POST");

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2014-04-02
    • 2021-02-20
    相关资源
    最近更新 更多