簡體   English   中英

為什么獲取請求有效,但發布不在Java servlet中

[英]why get requests are working, but post are not in the java servlets

我有一個servlet,我從get請求中調用它,它很好,但是當我使用此post請求調用它時,

private static void doPostToMultiPart() throws URISyntaxException,
            ClientProtocolException, IOException {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(
                "http://localhost:8080/ServletExample1/multipart1");
        HttpResponse response = client.execute(httpPost);
        System.out.println("response code = "
                + response.getStatusLine().getStatusCode());
        String responseString = new BasicResponseHandler()
                .handleResponse(response);
        System.out.println(responseString);
    }

我在handleResponse上遇到了一個異常,它是:

Exception in thread "main" org.apache.http.client.HttpResponseException: Not Found
    at org.apache.http.impl.client.AbstractResponseHandler.handleResponse(AbstractResponseHandler.java:69)
    at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:65)
    at com.clients.PostClient1.doPostToMultiPart(PostClient1.java:28)
    at com.clients.PostClient1.main(PostClient1.java:16)

我打印的狀態是404

我該怎么做?

注意

我可以給您servlet代碼,這很簡單,但是我雖然可以發出get請求,但是servlet工作正常,問題出在我的后客戶端請求中。

更新資料

當我這樣做

httpPost.addHeader("Content-Type", MediaType.TEXT_HTML);

它有效,但是當我這樣做時:

 httpPost.addHeader("Content-Type", MediaType.TEXT_HTML); 

我又得到了例外。 如果客戶端請求錯誤的內容類型,我想返回自定義消息。 請幫助

發布您的servlet,以及您使用的web.xml。 404表示找不到請求的資源。 您是否缺少doPost?

這意味着http://localhost:8080/ServletExample1/multipart1由於某種原因不是有效的POST URL。 放置請求的文件,讓我們看看他們說了什么。

(以長篇評論)

我知道它很奇怪,但是嘗試使用此方法發送Post(適當更改)

public static String sendPostV2(String data, String url) throws Exception {

    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
    org.apache.commons.httpclient.methods.PostMethod method = new org.apache.commons.httpclient.methods.PostMethod(url);
    if(data!=null){
       method.addParameter("data", data);
    }
    client.executeMethod(method);
    method.releaseConnection();
    try{
        return method.getResponseBodyAsString();
    }catch (Exception e){
        return null;
    }
}

我有一個非常相似的問題,我有兩個不同的send Post方法,因為一個方法可用於某些服務器,但不能全部用於其他服務器,而另一種方法則可用於其他服務器,第一個方法與您的代碼非常相似,第二個(上面的代碼)只是發送Post的另一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM