1. 程式人生 > >Java在傳送HTTP請求時,遇到身份驗證無法獲取到response內容的解決方法

Java在傳送HTTP請求時,遇到身份驗證無法獲取到response內容的解決方法

問題描述:

有些網站在接受HTTP請求時會先讓你進行身份認證,所以在用Java傳送HTTP請求時會出現401錯誤碼,無法正常獲取到想要的內容。

解決方法:

我以傳送get請求為例,說明解決方法。

public static String getMethod(String url) {
		String rb = null;
		
		HttpClient client = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		
		try {
			String str = "使用者名稱:密碼";   //這是能通過認證的使用者名稱和密碼
			byte[] b = str.getBytes("utf-8");
			str = new BASE64Encoder().encode(b);  //使用base64對使用者名稱:密碼進行加密
			
			getMethod.setRequestHeader("Authorization", "Basic " + str);   //在請求頭新增Authorization欄位    “Basic  ”這裡有個空格
			client.executeMethod(getMethod);
			rb = getMethod.getResponseBodyAsString();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}