HTTP Get Android with Basic Auth

I am new to REST services and I have been looking for a few hours on the internet ...

I have a REST service url that returns JSON data to me . Login (username and password) basic auth . I'm looking for a simple library / code snippet that allows me to inject uri, username and password and return a JSON string.

Any help would be appreciated!

+3


source to share


3 answers


Maybe you can try something like this:

StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("YOUR WEBSITE HERE");

// Add authorization header
httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));

// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(ParseJSON.class.toString(), "Failed to download file");
      }
} catch (ClientProtocolException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

      



As for writing JSONObject, check out this code snippet:

public void writeJSON() {
  JSONObject object = new JSONObject();
  try {
    object.put("name", "Jack Hack");
    object.put("score", new Integer(200));
    object.put("current", new Double(152.32));
    object.put("nickname", "Hacker");
  } catch (JSONException e) {
    e.printStackTrace();
  }
  System.out.println(object);
} 

      

+4


source


I am using the following library ...

http://loopj.com/android-async-http/ (No binding)

This allows the following syntax to be used to set up basic authentication and run a GET request to the server ...



AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password");
client.get("http://myurl.com", null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
                String json = new String(bytes); // This is the json.
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

      

It's dead easy and the library has a lot of mainstream support from some of the big apps on Google Play like Pintrest / Instagram, etc.

+1


source


Note for @erad's answer ( fooobar.com/questions/2168326 / ... )

The BasicScheme.authenticate method has been deprecated.

Instead of this:

httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));

      

you have to use this:

    String userName = "bla bla";
    String password = "top secret";
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
    Header basicAuthHeader = new BasicScheme(Charset.forName("UTF-8")).authenticate(credentials, httpGet, null);
    httpGet.addHeader(basicAuthHeader);

      

0


source







All Articles