当我试图通过基本身份验证,然后我的代码给我非法的参数异常

时间:2014-05-20 06:01:17

标签: java httpurlconnection

我有以下代码

String userName = "xyz.com";
String password = "xyz.com";
URL url = new URL("http://....")
URLConnection urlConnection = url.openConnection();
String userpass = userName + ":" + password;
String basicAuth = "Basic "
    + new String(new Base64().encode(userpass.getBytes()));
System.out.println("basic auth-->" + basicAuth);

urlConnection.setRequestProperty("Authorization: ", basicAuth);

InputStream inputStream = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);

int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
    sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");

,例外是

basic auth-->Basic flkja44dsfaj=
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic aHVuZ2FtYS5jb206aHVuZ2FtYS5jb20=

at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:482)
at sun.net.www.protocol.http.HttpURLConnection.isExternalMessageHeaderAllowed(HttpURLConnection.java:434)
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:2753)
at com.hungama.bbc.domObject.ContentDOMObjects.main(ContentDOMObjects.java:49)

1 个答案:

答案 0 :(得分:3)

尝试这种方式来编码用户名和密码:

final String userpass = userName + ":" + password;
final String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

你应该删除':'来自请求属性的字段名称:

urlConnection.setRequestProperty("Authorization", basicAuth);