使用HttpUrlConnection进行抢占式基本身份验证?

时间:2011-08-11 01:57:22

标签: java android http authentication basic-authentication

使用HttpUrlConnection使用抢先式基本http身份验证的最佳方法是什么。 (现在假设我不能使用HttpClient)。

编辑澄清:我正在使用Base64编码在请求标头中正确设置un / pw。是否需要设置任何其他标志或属性,或者是我为请求的基本auth标头设置了抢占式基本身份验证所需的全部内容?

6 个答案:

答案 0 :(得分:96)

如果您使用的是Java 8或更高版本,java.util.Base64可用:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);


然后正常使用连接。

如果您使用的是Java 7或更低版​​本,则需要一种方法将String编码为Base64,例如:

byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);

是的,这就是使用Basic Auth所需要做的一切。设置Request属性的代码应该在打开连接之后和获取输入或输出流之前立即完成。

答案 1 :(得分:2)

顺便提一下,如果您使用org.apache.commons.codec.binary.Base64并执行Base64.encodeBase64String(),如果其他人遇到同样的问题,那么也会出现安卓问题。你需要做Base64.encodeBase64()并得到一个byte []然后构造字符串。

它完全让我感到不安,因为在这两种方法之间结束的行结果会有所不同。

答案 2 :(得分:1)

答案 3 :(得分:0)

我也有这个问题。 现在我已经解决了这个问题。 我的代码是:

    URL url = new URL(stringUrl);

    String authStr = "MyAPIKey"+":"+"Password";
    System.out.println("Original String is " + authStr);

 // encode data on your side using BASE64
    byte[] bytesEncoded = Base64.encodeBase64(authStr .getBytes());
    String authEncoded = new String(bytesEncoded);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Authorization", "Basic "+authEncoded);

它可能会帮助许多其他人。 祝你好运。

答案 4 :(得分:0)

你需要这样做才能复制粘贴它很开心

    HttpURLConnection urlConnection;
    String url;
 //   String data = json;
    String result = null;
    try {
        String username ="danish.hussain@gmail.com";
        String password = "12345678";

        String auth =new String(username + ":" + password);
        byte[] data1 = auth.getBytes(UTF_8);
        String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
        //Connect
        urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", "Basic "+base64);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(10000);
        urlConnection.connect();
        JSONObject obj = new JSONObject();

        obj.put("MobileNumber", "+97333746934");
        obj.put("EmailAddress", "danish.hussain@dhl.com");
        obj.put("FirstName", "Danish");
        obj.put("LastName", "Hussain");
        obj.put("Country", "BH");
        obj.put("Language", "EN");
        String data = obj.toString();
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();
        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

        }else {
        //    return new String("false : "+responseCode);
        new String("false : "+responseCode);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 5 :(得分:-2)

关于Base64编码问题,我找到了这个库:http://sourceforge.net/projects/migbase64/

我还没有完全审查它,但是我将它用于上面显示的基本身份验证解决方案(以及图像编码/解码),并且它运行良好。它提供了是否包含换行符的参数。