java網絡編程

302重定向

重定向的目的url寫在header的Location屬性。
httpclient以GET發送請求時,http的返回碼是200,自動處理了重定向;
以POST發送請求時,http的返回碼是302,不自動處理重定向,處於佔用連接等待狀態。

HttpPost  request=new HttpPost(url);
HttpResponse response=httpclient.execute(request);
//釋放post請求
request.abort();
if(response.getStatusLine().getStatusCode()==302)
{
    String location=response.getLastHeader("Location").getValue();

}

java中的httpclient有兩種,一個是commons-httpclient,爲遺留版本不推薦使用;另一個是httpclient項目的httpcore-x.xxx.jar。

httpclient使用

HttpEntity  entity=response.getEntity();
//將字節流保存在一個byte數組中
byte[]  bytes=EntityUtils.toByteArray(entity);
//獲取Content-Type編碼信息
String charset=EntityUtils.getContentCharSet(entity);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章