HTTP POST request with authorization on android

前端 未结 2 1233
[愿得一人]
[愿得一人] 2020-12-07 21:57

When I set \"Authorization\" header with setHeader from HttpPost then hostname disappears from request and there is always error 400 (bad request) returned. Same code is wor

相关标签:
2条回答
  • 2020-12-07 22:27

    use simply this :

    String authorizationString = "Basic " + Base64.encodeToString(
                            ("your_login" + ":" + "your_password").getBytes(),
                            Base64.NO_WRAP); //Base64.NO_WRAP flag
                    post.setHeader("Authorization", authorizationString);
    
    0 讨论(0)
  • Thanks to Samuh for a hint :) There was an extra newline character inserted which has no means in GET requests, but matters in POST ones. This is proper way to generate Authorization header in android (in getB64Auth in this case):

     private String getB64Auth (String login, String pass) {
       String source=login+":"+pass;
       String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
       return ret;
     }
    

    The Base64.NO_WRAP flag was lacking.

    0 讨论(0)
提交回复
热议问题