TomCB
TomCB

Reputation: 4063

HTTP Get Android with Basic Auth

I'm new to REST services and I'm looking for a few hours around the web...

I have a REST service url that gives me back JSON data. The login (username & password) are basic auth. I'm looking for a simple library/code snippet that lets me insert the uri, username & password and give me back the JSON string.

Any help would be appreciated!

Upvotes: 3

Views: 12392

Answers (3)

lidox
lidox

Reputation: 1971

Note to @erad's answer (https://stackoverflow.com/a/26176707/1386969)

The method BasicScheme.authenticate is deprecated.

Instead of using this:

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

you should 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);

Upvotes: 1

BenjaminPaul
BenjaminPaul

Reputation: 2931

I use the following library...

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

This allows you to use the following syntax to set the basic authentication and fire 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 alot of main stream support from some of the large applications on Google Play such as Pintrest / Instagram etc!

Upvotes: 1

erad
erad

Reputation: 1786

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 a 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);
} 

Upvotes: 5

Related Questions