Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. package info.androidhive.jsonparsing;
  2.  
  3. import android.util.Log;
  4.  
  5. import java.io.BufferedInputStream;
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.net.HttpURLConnection;
  11. import java.net.MalformedURLException;
  12. import java.net.ProtocolException;
  13. import java.net.URL;
  14.  
  15. /**
  16. * Created by Ravi Tamada on 01/09/16.
  17. * www.androidhive.info
  18. */
  19. public class HttpHandler {
  20.  
  21. private static final String TAG = HttpHandler.class.getSimpleName();
  22.  
  23. public HttpHandler() {
  24. }
  25.  
  26. public String makeServiceCall(String reqUrl) {
  27. String response = null;
  28. try {
  29. URL url = new URL(reqUrl);
  30. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  31. conn.setRequestMethod("GET");
  32. // read the response
  33. InputStream in = new BufferedInputStream(conn.getInputStream());
  34. response = convertStreamToString(in);
  35. } catch (MalformedURLException e) {
  36. Log.e(TAG, "MalformedURLException: " + e.getMessage());
  37. } catch (ProtocolException e) {
  38. Log.e(TAG, "ProtocolException: " + e.getMessage());
  39. } catch (IOException e) {
  40. Log.e(TAG, "IOException: " + e.getMessage());
  41. } catch (Exception e) {
  42. Log.e(TAG, "Exception: " + e.getMessage());
  43. }
  44. return response;
  45. }
  46.  
  47. private String convertStreamToString(InputStream is) {
  48. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  49. StringBuilder sb = new StringBuilder();
  50.  
  51. String line;
  52. try {
  53. while ((line = reader.readLine()) != null) {
  54. sb.append(line).append('\n');
  55. }
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. } finally {
  59. try {
  60. is.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. return sb.toString();
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement