天天看点

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;

    }