Android:使用AsyncTask进行HTTP GET请求?

20

我是Android开发的新手。我的问题是,为了进行HTTP GET请求(JSON响应),我是否应该使用AsyncTask?这样正确吗?如果确实如此,有人知道在哪里可以看到这方面的示例吗?如果不是,能否纠正我?谢谢!


可能是重复的问题:如何在Android中进行HTTP请求 - 323go
可能是AsyncTask Android example的重复问题。 - U.Swap
AsyncTask自Android 11起已被弃用。 - Peter Bruins
7个回答

36

是的,你说得对,Asynctask用于处理短时间运行的任务,例如连接到网络。同时它也用于后台任务,这样就不会阻塞UI线程或因为在UI/Main线程中无法进行网络连接而出现异常。

例子:

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {


@Override
protected void onPreExecute() {
    super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... urls) {
    try {

        //------------------>>
        HttpGet httppost = new HttpGet("YOU URLS TO JSON");
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        // StatusLine stat = response.getStatusLine();
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);


            JSONObject jsono = new JSONObject(data);

            return true;
        }


    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return false;
}

protected void onPostExecute(Boolean result) {

}

4
"org.apache.http.legacy" 已经被弃用,有其他实现方式吗? - Brampage

4

是的,你有三种选择

  1. 使用AsyncTask
  2. 你可以使用Handler
  3. 或者你可以使用一个seperate Thread

最好的选择是AsyncTask。你需要在AsyncTask的doInBackground方法中实现你的网络调用,并在postExecute方法中更新UI或对结果进行任何想要的操作。

你可以参照这个教程来满足你的需求。

代码片段

@Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

注意: 由于DefaultHttpClient已经被弃用,你可以使用HttpClientBuilder


4
protected String doInBackground(String... strings) {

    String response = "";

    response = ServiceHandler.findJSONFromUrl("url");
    data = response;
    return response;
}

public class ServiceHandler {

    // Create Http connection And find Json

    public static String findJSONFromUrl(String url) {
        String result = "";
        try {
            URL urls = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
            conn.setReadTimeout(150000); //milliseconds
            conn.setConnectTimeout(15000); // milliseconds
            conn.setRequestMethod("GET");

            conn.connect();

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }
                result = sb.toString();
            } else {

                return "error";
            }


        } catch (Exception e) {
            // System.out.println("exception in jsonparser class ........");
            e.printStackTrace();
            return "error";
        }

        return result;
    } // method ends
}

3

看看这个链接谷歌提供的示例,这个也不错

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  // constructor
  public JSONParser() {
  }
  public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
      // defaultHttpClient
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "n");
      }
      is.close();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
  }
}

不推荐使用的解决方案! - Oskar

3

以下是在ASyncTask类中使用简单的HttpsURLConnection进行Https POST/GET网络API调用的示例,同时包括数据包头和主体中的JSONObject

import android.os.AsyncTask;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Class to handle BasicAuth post web-api call.
 */
public class Information extends AsyncTask<String, String, String> {

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

        try {
            // Creating & connection Connection with url and required Header.
            URL url = new URL("https://example.com/wp-json/jwt-auth/v1/token");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("header-param_3", "value-3");
            urlConnection.setRequestProperty("header-param_4", "value-4");
            urlConnection.setRequestProperty("Authorization", "Basic Y2tfNDIyODg0NWI1YmZiZT1234ZjZWNlOTA3ZDYyZjI4MDMxY2MyNmZkZjpjc181YjdjYTY5ZGM0OTUwODE3NzYwMWJhMmQ2OGQ0YTY3Njk1ZGYwYzcw");
            urlConnection.setRequestMethod("POST");   //POST or GET
            urlConnection.connect();

            // Create JSONObject Request
            JSONObject jsonRequest = new JSONObject();
            jsonRequest.put("username", "user.name");
            jsonRequest.put("password", "pass@123");

            // Write Request to output stream to server.
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            out.write(jsonRequest.toString());
            out.close();

            // Check the connection status.
            int statusCode = urlConnection.getResponseCode();
            String statusMsg = urlConnection.getResponseMessage();

            // Connection success. Proceed to fetch the response.
            if (statusCode == 200) {
                InputStream it = new BufferedInputStream(urlConnection.getInputStream());
                InputStreamReader read = new InputStreamReader(it);
                BufferedReader buff = new BufferedReader(read);
                StringBuilder dta = new StringBuilder();
                String chunks;
                while ((chunks = buff.readLine()) != null) {
                    dta.append(chunks);
                }
                String returndata = dta.toString();
                return returndata;
            } else {
                //Handle else case
            }
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

在这里,Authentication(头参数)的值是[API-key]:[API-Secret]Base64编码值,在其前面添加"Basic "字符串。

在Android Studio中,使用Gradle入口:

compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

0

AsyncTask确实管理其线程池,但它并不针对网络活动进行优化。实际上,如果您有许多HTTP请求发送到同一服务器,则最好在同一线程上保持它们,以便尽可能地重用持久连接,这样可以更好地控制内存消耗和整体性能。AsyncTask并未考虑此类问题。

与其自己编写异步HTTP客户端,不如考虑使用其中的几个可用库之一。一些聪明的人投入了大量精力来使这些库健壮、灵活且快速。


有哪些可用的异步HTTP客户端库?我开始实现一个,但觉得自己在重复造轮子。 - Gregory Stein
@GregoryStein,你可以开始在Google搜索框中输入这个问题。如果与你相关,请加上“android”这个词。 - Alex Cohn
有很多像 retrofitionvolleyokhttp 等的框架。 - Kaushik

0

这是进行POST请求并以JSON格式向服务器请求的代码。

{"emailId":"test123@gmail.com","emailIdOTP":"123456","phoneNo":"1111111111"}

异步任务:

public class GetAsynTask extends AsyncTask<String, String, String> {

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

            try {
                // Creating & connection Connection with url and required Header.
                URL url = new URL(JWT_URL);
                HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestMethod("POST");   //POST or GET
                urlConnection.connect();

                // Create JSONObject Request
                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("emailId", "test123@gmail.com");
                jsonRequest.put("emailIdOTP", "123456");
                jsonRequest.put("phoneNo", "1111111111");


                // Write Request to output stream to server.
                OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                out.write(jsonRequest.toString());
                out.close();

                // Check the connection status.
                int statusCode = urlConnection.getResponseCode();

                // Connection success. Proceed to fetch the response.
                if (statusCode == 200) {
                    InputStream it = new BufferedInputStream(urlConnection.getInputStream());
                    InputStreamReader read = new InputStreamReader(it);
                    BufferedReader buff = new BufferedReader(read);
                    StringBuilder dta = new StringBuilder();
                    String chunks;
                    while ((chunks = buff.readLine()) != null) {
                        dta.append(chunks);
                    }
                    String returndata = dta.toString();
                    return returndata;
                } else {
                    Toast.makeText(SplashActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String resultData) {
            super.onPostExecute(resultData);
            try {
                JSONObject obj = new JSONObject(resultData);
               String name= obj.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接