Advertisement
andyshon

SimpleHttpRequest

Feb 12th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. public class GetUrlContentTask extends AsyncTask<String, Integer, String> {
  2.     protected String doInBackground(String... urls) {
  3.         URL url = null;
  4.         HttpURLConnection connection = null;
  5.         try {
  6.             url = new URL(urls[0]);
  7.             connection = (HttpURLConnection) url.openConnection();
  8.             connection.setRequestMethod("GET");
  9.             connection.setDoOutput(true);
  10.             connection.setConnectTimeout(5000);
  11.             connection.setReadTimeout(5000);
  12.             connection.connect();
  13.         } catch (IOException e) {
  14.             e.printStackTrace();
  15.         }
  16.  
  17.         BufferedReader rd;
  18.         StringBuilder content = new StringBuilder();
  19.         try {
  20.             assert connection != null;
  21.             rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  22.             String line;
  23.             while ((line = rd.readLine()) != null) {
  24.                 content.append(line).append("\n");
  25.             }
  26.             return content.toString();
  27.         } catch (IOException e) {
  28.             e.printStackTrace();
  29.         }
  30.  
  31.         return content.toString();
  32.     }
  33.  
  34.     protected void onProgressUpdate(Integer... progress) {
  35.     }
  36.  
  37.     protected void onPostExecute(String result) {
  38.         System.out.println("result = " + result);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement