java中httpclent以post方式提交請求時,http返回碼是302重定向時,不自動跳轉的處理
阿新 • • 發佈:2019-01-03
場景:
介面A:請求地址為http://www.test.com/test
介面A的功能,會把接收到的引數url寫入到header的Location屬性中
在java中,使用httpclient傳送請求,
在以get方式傳送請求時,http的返回碼是200,自動處理了重定向
在以post方式傳送請求時,http的返回碼是302,不自動重定向,而且處於佔用連線等待狀態
此時的處理:
針對返回結果,處理返回碼為302的情況
HttpPost httpPost = new HttpPost(url); //請求地址 StringEntity reqEntity = new StringEntity(str);//表單 HttpResponse response = httpclient.execute(httppost); httppost.abort();//釋放post請求 //處理http返回碼302的情況 if (response.getStatusLine().getStatusCode() == 302) { String locationUrl=response.getLastHeader("Location").getValue(); get(locationUrl);//跳轉到重定向的url }