HTTP使用基本身份验证获取Android

时间:2014-10-03 09:34:14

标签: android http-basic-authentication

我是REST服务的新手,我正在网上寻找几个小时...

我有一个REST服务网址,可以返回 JSON数据。 登录名(用户名和密码)为基本身份验证。 我正在寻找一个简单的库/代码段,它允许我插入uri,用户名和&密码,并给我回JSON字符串。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:5)

也许你可以尝试这样的事情:

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

至于编写JSONObject,请查看此代码段:

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

答案 1 :(得分:1)

我使用以下库...

http://loopj.com/android-async-http/(无附属)

这允许您使用以下语法设置基本身份验证并向服务器发出GET请求...

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) {

            }
        });

它非常简单,图书馆有很多主流支持来自Google Play上的一些大型应用程序,如Pintrest / Instagram等!

答案 2 :(得分:0)

请注意@ erad的回答(https://stackoverflow.com/a/26176707/1386969

不推荐使用 BasicScheme.authenticate 方法。

而不是使用它:

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

你应该用这个:

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