Android: AsyncTask to make an HTTP GET Request?

前端 未结 7 762
失恋的感觉
失恋的感觉 2020-11-27 19:46

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 a

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 20:24

    Here is simple HttpsURLConnection in ASyncTask class for Https POST/GET web-API calling along with packet-header and JSONObject in body.

    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 {
    
        @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 Base64 encoded value of [API-key]:[API-Secret] appending the "Basic " string in start.

    In Android Studio, use the Gradle entry as:

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

提交回复
热议问题