今天寫一個小功能需要通過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