JAVA HTTP客户端和Serlvlet

时间:2014-01-31 11:17:00

标签: java http tomcat servlets client

我正在使用Apache Tomcat,我想将数据发送到http服务器并从HTTP服务器(来自servlet)获取响应。

问题

当我使用 HTTP客户端发送数据时,似乎未传递数据(servlet发送的参数不显示)。当我通过 HTTP浏览器(Chrome)模拟相同内容时,一切似乎都没问题。

Bellow是我的servlet和我的http客户端的例子。

我的HTTP Servlet

public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        PrintWriter out = res.getWriter();
        out.println("This ervlet requires POST but received GET");
        out.close();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        for (String name : request.getParameterMap().keySet()) {
            out.write("PARAMETER :" + name);
            out.write("\n");
        }

        for (Part name : request.getParts()) {
            out.write("MULTIPART PARAMETER :" + name.getName());
            out.write("\n");
        }

        String p1 = request.getParameter("input1");
        out.write("RECEIVED PARAMETER:" + p1);
        out.write("\n");

        out.close();
    }
}

我的HTTP客户端

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://example.com:8080" +
                    "/myservlet");

            FileBody bin = new FileBody(new File("file1.txt"));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("input1", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    PrintWriter sWriter = new PrintWriter(System.out);
                    IOUtils.copy(resEntity.getContent(), sWriter, "UTF-8");
                    sWriter.close();
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}
  

OUTPUT:执行请求POST

     

http://example.com:8080/myservlet HTTP / 1.1

     

---------------------------------------- HTTP / 1.1 200 OK

     

RECEIVED PARAMETER:null

浏览器客户端(测试) broswer POST按预期工作:

<form name="input" action="http://example.com:8080/servlet" method="post">
<input type="text" name="input1">
<input type="submit" value="Submit">
</form>
  

OUTPUT:PARAMETER:input1

     

收到的参数:AAAAAAAA

更新: 浏览器代码

Request URL:http://localhost:8080/servlet
Request Method:POST
Status Code:200 OK
Request Headersview parsed
POST /LyticsRemote/flexi HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 10
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.102 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate,sdch
Accept-Language: cs,en-GB;q=0.8,en;q=0.6
Cookie: JSESSIONID=9BD73E186BC8A081AB87C8EF58483523
Form Dataview sourceview URL encoded
input1:aaa
Response Headersview source
Content-Length:41
Content-Type:text/html;charset=ISO-8859-1
Date:Fri, 31 Jan 2014 11:46:54 GMT
Server:Apache-Coyote/1.1

1 个答案:

答案 0 :(得分:0)

解决方案是将 getParameters 方法添加到servlet中,以便最终代码为:

public class FlexiServlet extends HttpServlet {
    private FileItem fileItem;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        PrintWriter out = res.getWriter();
        out.println("This ervlet requires POST but received GET");
        out.close();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        boolean success = getParameters(request, out);
        out.write(" XXXXXXXXXXXXXXXXX" + success);
        out.write(" XXXXXXXXXXXXXXXXX" + fileItem);
        out.write("\n");
        for (String name : request.getParameterMap().keySet()) {
            out.write("PARAMETER :" + name);
            out.write("\n");
        }

        for (Part name : request.getParts()) {
            out.write("MULTIPART PARAMETER :" + name.getName());
            out.write("\n");
        }

        String p1 = request.getParameter("input1");
        out.write("RECEIVED PARAMETER:" + p1);
        out.write("\n");

        out.close();
    }

    public boolean getParameters(HttpServletRequest request, PrintWriter out) {
        List fileItemsList = null;
        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                ServletFileUpload servletFileUpload = new ServletFileUpload(
                        new DiskFileItemFactory());
                try {
                    fileItemsList = servletFileUpload.parseRequest(request);
                } catch (FileUploadException ex) {
                }
                String optionalFileName = "";
                Iterator it = fileItemsList.iterator();
                while (it.hasNext()) {
                    FileItem fileItemTemp = (FileItem) it.next();
                    if (fileItemTemp.isFormField()) {
                        // for other form fields that are not multipart
                        // if (fileItemTemp.getFieldName().equals("commonName"))
                        // {
                        // commonName = fileItemTemp.getString();
                        // }
                        out.write("AAAAAAAAAAAA " + fileItemTemp.getFieldName());
                    } else {
                        if (fileItemTemp.getFieldName().equals("media_file")) {
                            fileItem = fileItemTemp;
                        }
                        out.write("BBBBBBBBBBBBBB " + fileItemTemp.getFieldName());

                    }
                }
            }
        } catch (Exception e) {
        }
        return true;
    }
}