Authorization for github.com on Android

隐身守侯 提交于 2019-11-30 10:20:52
pelson

I know you want it in Java, but you might be interested in an answer I just provided to another question for further Python examples.

In order to authenticate I had to specifically state the type of authentication (what follows is Python code):

base64string = base64.encodestring('%s:%s' % (username, passwd)).replace('\n', '')
req.add_header("Authorization", "Basic %s" % base64string)

But it doesn't appear that you are adding the "Basic " prefix. Try adding that in and seeing if you get any success.

def encoded = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
request.setHeader("Authorization", "Basic " + encoded);
Arhat Baid

Finally, after wasting one full day I got it. This is my working code.Just pass uName & password, it'll return JSON string.

public String Authorization(String username, String password) {
    String result = null;
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("https://api.github.com/user");

    String encode = Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT).replace("\n", "");
    httpGet.setHeader("Authorization", "Basic " + encode);
    try {
        HttpResponse httpResponse = client.execute(httpGet);
        InputStream inputStream = httpResponse.getEntity().getContent();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder stringBuilder = new StringBuilder();
        String bufferedStrChunk = null;
        while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
            stringBuilder.append(bufferedStrChunk);
        }

        result = stringBuilder.toString();

    } catch (ClientProtocolException cpe) {
        System.out.println("ClientProtocolException :" + cpe);
        cpe.printStackTrace();
    } catch (IOException ioe) {
        System.out.println("IOException :" + ioe);
        ioe.printStackTrace();
    }

    return result;
}

Reference links : Link1 & Link for basci Auth & Link for web flow:Android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!