Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HTTP使用基本身份验证获取Android_Android_Basic Authentication - Fatal编程技术网

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

HTTP使用基本身份验证获取Android,android,basic-authentication,Android,Basic Authentication,我是REST服务的新手,我正在网上找几个小时 我有一个REST服务url,它返回JSON数据。 登录名(用户名和密码)为基本身份验证。 我正在寻找一个简单的库/代码片段,它允许我插入uri、用户名和密码并返回JSON字符串 任何帮助都将不胜感激 也许你可以试试这样的东西: StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new H

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

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


任何帮助都将不胜感激

也许你可以试试这样的东西:

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

我使用以下库

(无隶属关系)

这允许您使用以下语法设置基本身份验证并向服务器发出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等)的主流支持

@erad回答的注释()

已弃用方法基本方案.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);

可能的重复给了我“错误:找不到符号方法setEntity(UrlEncodedFormEntity)”Oops。忘记了您不允许在Http GET请求中添加这些内容-仅限POST。请参阅我的最新答案@TomCBI获得状态码401,我想这意味着存在一些问题authorisation@TomCB您是正确的,401通常意味着您的凭据无效。但是您能够使用android代码执行HTTP GET请求,对吗?如果这回答了你的问题,请投赞成票,并指出这是正确的答案。这给了我一个错误:onSucces&onFailure:“Method不重写它的超类中的Method”你准确地复制并粘贴了代码?我只是从一个工作示例中粘贴了这个。看看我链接的网站就知道了。。有很多例子。4年后,我会尝试