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