向HttpURLConnection 要求新增標頭
嘗試向HttpURLConnection 要求新增標頭時,您可能會遇到伺服器無法確認的情況標頭頭資訊。如果使用 setRequestProperty()設定請求屬性無法解決問題,請考慮以下解決方案:
解決方案:
確保標頭設定正確,請嘗試執行下列步驟:
建立一個新實例HttpURLConnection:
URL myURL = new URL(serviceURL); HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
準備標頭值:
String userCredentials = "username:password"; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
設定“授權” header:
myURLConnection.setRequestProperty ("Authorization", basicAuth);
設定連接:
myURLConnection.setRequestMethod("POST"); // Assuming a POST request myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length); myURLConnection.setRequestProperty("Content-Language", "en-US"); myURLConnection.setUseCaches(false); myURLConnection.setDoInput(true); myURLConnection.setDoOutput(true);
以上是為什麼我的 HttpURLConnection 請求中的標頭未被識別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!