Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fr.benjaminthomas.projet_github.Async;
- import android.os.AsyncTask;
- import android.util.Base64;
- import android.util.Log;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- /**
- * Created by benjaminthomas on 11/04/2017.
- */
- public class HttpGetRequest extends AsyncTask<String, Void, String> {
- private String username;
- private String password;
- public HttpGetRequest() {}
- public HttpGetRequest(String username, String password) {
- this.username = username;
- this.password = password;
- }
- @Override
- protected String doInBackground(String... params) {
- URL urlCould;
- HttpURLConnection connection;
- InputStream inputStream = null;
- try {
- String url = params[0];
- urlCould = new URL(url);
- String credentials = username + ":" + password;
- String basicAuth = "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.DEFAULT));
- connection = (HttpURLConnection) urlCould.openConnection();
- connection.setConnectTimeout(30000);
- connection.setReadTimeout(30000);
- connection.setRequestMethod("GET");
- if (username != null){
- connection.setRequestProperty("Authorization", basicAuth);
- }
- connection.connect();
- inputStream = connection.getInputStream();
- //Log.d("test",inputStream.toString());
- } catch (IOException IOEx){
- Log.e("HTTP", "HTTP failed to fetch data "+IOEx.getMessage());
- return null;
- }
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- StringBuilder sb = new StringBuilder();
- String line;
- try {
- while ((line = reader.readLine()) != null) {
- sb.append(line).append("\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- Log.d("HTTP",sb.toString());
- return sb.toString();
- }
- @Override
- protected void onPostExecute(String result){
- super.onPostExecute(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement