
對 HttpURLConnection 中的標頭添加進行故障排除
嘗試將標頭附加到 HttpURLConnection 請求時,setRequestProperty()方法可能不會總是按預期運行,導致伺服器收不到預期的內容
一個潛在的解決方案,已被證明在TomCat 環境中有效,是利用以下程式碼片段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ( "Authorization" , basicAuth);
myURLConnection.setRequestMethod( "POST" );
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);
|
登入後複製
此程式碼是專門為POST 要求設計的,但您可以輕鬆地如有必要,請將其修改為GET 或其他請求類型。透過套用這些更新,您應該能夠成功地將標頭新增至 HttpURLConnection 請求中,並確保伺服器收到預期的標頭。
以上是如何確保在 HttpURLConnection 請求中收到標頭?的詳細內容。更多資訊請關注PHP中文網其他相關文章!