Android: AsyncTask to make an HTTP GET Request?

前端 未结 7 759
失恋的感觉
失恋的感觉 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:09

    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
    }
    

提交回复
热议问题