Advertisement
Guest User

Untitled

a guest
May 4th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. package fr.benjaminthomas.projet_github.Async;
  2.  
  3. import android.os.AsyncTask;
  4. import android.util.Base64;
  5. import android.util.Log;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.net.HttpURLConnection;
  12. import java.net.MalformedURLException;
  13. import java.net.URL;
  14.  
  15. /**
  16. * Created by benjaminthomas on 11/04/2017.
  17. */
  18.  
  19. public class HttpGetRequest extends AsyncTask<String, Void, String> {
  20. private String username;
  21. private String password;
  22.  
  23. public HttpGetRequest() {}
  24.  
  25. public HttpGetRequest(String username, String password) {
  26. this.username = username;
  27. this.password = password;
  28. }
  29.  
  30. @Override
  31. protected String doInBackground(String... params) {
  32.  
  33. URL urlCould;
  34. HttpURLConnection connection;
  35. InputStream inputStream = null;
  36.  
  37. try {
  38. String url = params[0];
  39. urlCould = new URL(url);
  40. String credentials = username + ":" + password;
  41. String basicAuth = "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.DEFAULT));
  42. connection = (HttpURLConnection) urlCould.openConnection();
  43. connection.setConnectTimeout(30000);
  44. connection.setReadTimeout(30000);
  45. connection.setRequestMethod("GET");
  46.  
  47. if (username != null){
  48. connection.setRequestProperty("Authorization", basicAuth);
  49. }
  50.  
  51. connection.connect();
  52.  
  53. inputStream = connection.getInputStream();
  54. //Log.d("test",inputStream.toString());
  55.  
  56. } catch (IOException IOEx){
  57. Log.e("HTTP", "HTTP failed to fetch data "+IOEx.getMessage());
  58. return null;
  59. }
  60.  
  61. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  62. StringBuilder sb = new StringBuilder();
  63. String line;
  64.  
  65. try {
  66. while ((line = reader.readLine()) != null) {
  67. sb.append(line).append("\n");
  68. }
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. } finally {
  72. try {
  73. inputStream.close();
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78.  
  79. Log.d("HTTP",sb.toString());
  80.  
  81. return sb.toString();
  82. }
  83.  
  84. @Override
  85. protected void onPostExecute(String result){
  86. super.onPostExecute(result);
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement