今天写一个小功能需要通过http请求获取一些返回数据,但是在登陆时是需要进行用户名和密码的校验的。写好之后请求,返回异常Java Server returned HTTP response code: 401
下面是修改之后的代码:
private static void httpRequest(){
String username = "XX";
String password = "XX";
String requestURL = "https://XXXX"; URL url;
URLConnection connection = null;
try {
url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
String encoding = new String(Base64.encode(new String(username+":"+password).getBytes()));
((HttpURLConnection) connection).setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "UTF-8");
connection.setRequestProperty( "Authorization","Basic "+encoding);
connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
File fp = new File("/tmp/xml.txt");// 获取整个返回的结果入/tmp/xml.txt中
PrintWriter pfp= new PrintWriter(fp);
pfp.print(in.readLine());// 返回结果只有一行……
pfp.close(); in.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
注意事项:
1. 第15行,Basic 后面有一个空格
参考:http://*.com/questions/22677930/java-server-returned-http-response-code-401