1. 程式人生 > >HTTP的DELETE方法Body傳遞參數問題解決

HTTP的DELETE方法Body傳遞參數問題解決

red operation style thread source overflow stream accep logs

理論上,Delete method是通過url傳遞參數的,如果使用body傳遞參數呢?

前提:

使用HttpClient發送http請求

問題:

httpDelete對象木有setEntity方法

解決方案:覆蓋HttpEntityEnclosingRequestBase,重新實現一個HttpDelete類

源碼如下:

import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

import java.net.URI;

/** * Description: HttpDelete 使用 body 傳遞參數 * 參考:https://stackoverflow.com/questions/3773338/httpdelete-with-body * <p/> * User: lishaohua * Date: 2017/11/29 12:58 */ @NotThreadSafe public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE";
/** * 獲取方法(必須重載) * * @return */ @Override public String getMethod() { return METHOD_NAME; } public HttpDeleteWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithBody(final URI uri) { super(); setURI(uri); }
public HttpDeleteWithBody() { super(); } }

該方法是參考HttpClient的HttpPost類實現的,查看HttpPost的源碼:

import java.net.URI;

import org.apache.http.annotation.NotThreadSafe;

/**
 * HTTP POST method.
 * <p>
 * The HTTP POST method is defined in section 9.5 of
 * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
 * <blockquote>
 * The POST method is used to request that the origin server accept the entity
 * enclosed in the request as a new subordinate of the resource identified by
 * the Request-URI in the Request-Line. POST is designed to allow a uniform
 * method to cover the following functions:
 * <ul>
 *   <li>Annotation of existing resources</li>
 *   <li>Posting a message to a bulletin board, newsgroup, mailing list, or
 *     similar group of articles</li>
 *   <li>Providing a block of data, such as the result of submitting a form,
 *     to a data-handling process</li>
 *   <li>Extending a database through an append operation</li>
 * </ul>
 * </blockquote>
 * </p>
 *
 * @since 4.0
 */
@NotThreadSafe
public class HttpPost extends HttpEntityEnclosingRequestBase {

    public final static String METHOD_NAME = "POST";

    public HttpPost() {
        super();
    }

    public HttpPost(final URI uri) {
        super();
        setURI(uri);
    }

    /**
     * @throws IllegalArgumentException if the uri is invalid.
     */
    public HttpPost(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

}

沒錯,就是原封不動抄的!!!

如何使用?

很簡單,替換原來的構造方法:

/**
         * 02、構建HttpDelete對象
         */
        //被拋棄的HttpDelete,因為不支持body傳遞參數
        //HttpDelete httpDelete = new HttpDelete(proxyURL);
        //使用我們重載的HttpDelete
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(proxyURL);
        // 處理請求協議
        httpDelete.setProtocolVersion(super.doProtocol(servletRequest));
        // 處理請求頭
        httpDelete.setHeaders(super.doHeaders(servletRequest));
        // 處理請求體
        try {
            InputStream inputStream = servletRequest.getInputStream();
            httpDelete.setEntity(new InputStreamEntity(inputStream));

            /*StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = null;
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }else {
                stringBuilder.append("");
            }
            logger.info("request params---------->"+stringBuilder.toString());
            httpDelete.setEntity(new StringEntity(stringBuilder.toString(), ContentType.APPLICATION_JSON));*/
        } catch (IOException e) {
            logger.error("set httpDelete entity fail", e);
            // 取流失敗,則要拋出異常,阻止本次請求
            throw new RuntimeException(e);
        }

        logger.info("DELETE method handler end...");

參考文章

https://stackoverflow.com/questions/3773338/httpdelete-with-body

https://www.cnblogs.com/heyus/p/3790234.html

HTTP的DELETE方法Body傳遞參數問題解決