Android:AsyncTask 发出 HTTP GET 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24399294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:05:28  来源:igfitidea点击:

Android: AsyncTask to make an HTTP GET Request?

androidandroid-asynctaskhttprequest

提问by Mario A Guzman

I'm new to Android development. My question is, do I use AsyncTask in order to make an HTTP GET request (JSON response)? Is this correct? Does anyone know where I can see an example of this if this is indeed true? If not, could you correct me? Thanks!

我是 Android 开发的新手。我的问题是,我是否使用 AsyncTask 来发出 HTTP GET 请求(JSON 响应)?这样对吗?如果这确实是真的,有谁知道我在哪里可以看到这样的例子?如果没有,你能纠正我吗?谢谢!

回答by Rod_Algonquin

Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.

是的,你是对的,Asynctask 用于短期运行的任务,例如连接到网络。它也用于后台任务,这样您就不会因为无法在 UI/主线程中进行网络连接而阻塞 UI 线程或获得异常。

example:

例子:

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) {

}

回答by Kaushik

Yes you have 3 choices

是的,您有 3 个选择

  1. Using AsyncTask
  2. You can use Handler
  3. or you can use a seperate Thread.
  1. 使用异步任务
  2. 您可以使用处理程序
  3. 或者您可以使用seperate Thread.

Best choice is AsyncTask. You have to implement your network callin doInBackgroundmethod of AsyncTaskand in postExecutemethod update the UIor whatever you want to do with the result.

最好的选择是 AsyncTask。您必须实现您的network callindoInBackground方法AsyncTask和 inpostExecute方法更新UI或您想要对结果执行的任何操作。

you can follow follow this tutorial for your requirement

您可以按照本教程进行操作以满足您的要求

code snippet

代码片段

@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;
    }

N.B:As DefaultHttpClientis deprecated you can use HttpClientBuilder

注意:由于DefaultHttpClient已弃用,您可以使用HttpClientBuilder

回答by Cho Hee

Check this out LINKand emaple from googlethis one good too

看看这个链接谷歌的emaple这个也不错

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;
  }
}

回答by Rishabh Dixit

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
}

回答by Rahul Raina

Here is simple HttpsURLConnectionin ASyncTaskclass for Https POST/GET web-API calling along with packet-header and JSONObjectin body.

下面是简单HttpsURLConnectionASyncTask类HTTPS POST / GET Web的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;
    }

}

Here the value of Authentication(Header-parameter) is the Base64encoded value of [API-key]:[API-Secret]appending the "Basic "string in start.

这里Authentication(Header-parameter)的Base64值是在start中[API-key]:[API-Secret]附加"Basic "字符串的编码值。

In Android Studio, use the Gradleentry as:

在 Android Studio 中,使用Gradle条目作为:

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

回答by Alex Cohn

AsyncTask does manage its thread pool, but it is not optimized for network activity. Actually, if you have many HTTP requests to the same server, it is better both in terms of memory consumption and overall performance to keep them on the same thread, and reuse a persistent connection, whenever possible. AsyncTask does not consider such issues.

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

Instead of forging your own asynchronous HTTP client, consider using one of the few available libraries. Some smart people invested quite a lot of thought into making these robust, flexible and fast.

与其构建自己的异步 HTTP 客户端,不如考虑使用为数不多的可用库之一。一些聪明人投入了大量心思来使这些强大、灵活和快速。

回答by Gyan Swaroop Awasthi

This is the code which conduct the post request and requests server in the form of json.

这是以json的形式进行post请求和请求服务器的代码。

{"emailId":"[email protected]","emailIdOTP":"123456","phoneNo":"1111111111"}

AsyncTask:

异步任务:

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", "[email protected]");
                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();
            }
        }
    }