天天看點

PostMethod送出302錯誤

301,302 都是http狀态的編碼,都代表着某個url發生了轉移,不同之處在于:

301 redirect: 301 代表永久性轉移(permanently moved)。

302 redirect: 302 代表暫時性轉移(temporarily moved )。

這是很官方的說法,那麼它們的差別到底是什麼呢?

這裡隻說解決方法,不針對這2個狀态進行詳解。

    /**

     * 執行post送出

     *

     * @return

     * @author shanhy

     */

    private static string getpostresponse(string url, part[] parts) {

        postmethod mpost = new postmethod(url);

        mpost.addrequestheader("content", "text/html,charset=gbk");

        mpost.setrequestentity(new multipartrequestentity(parts, mpost.getparams()));

        try {

            int statuscode = httpclient.executemethod(mpost);

            string responsebody = "";

            if (statuscode == httpstatus.sc_moved_permanently || statuscode == httpstatus.sc_moved_temporarily) {

                header locationheader = mpost.getresponseheader("location");

                string location = null;

                if (locationheader != null) {

                    location = locationheader.getvalue();

                    responsebody = getpostresponse(location, parts);// 用跳轉後的頁面重新請求。

                }

            } else if (statuscode == httpstatus.sc_ok) {

                responsebody = mpost.getresponsebodyasstring();

            }

//            system.out.println(responsebody);

            if (statuscode == httpstatus.sc_ok) {// 成功

                return null;

            mpost.releaseconnection();

            return responsebody;

        } catch (httpexception e) {

            e.printstacktrace();

        } catch (unsupportedencodingexception e) {

        } catch (ioexception e) {

        }

        return null;

    }