简体   繁体   English

检查HTTP POST请求的内容类型到Java servlet

[英]Checking Content-Type of HTTP POST Request to Java servlet

I've written a simple servlet that accepts HTTP POST requests and sends back a short response. 我编写了一个简单的servlet,它接受HTTP POST请求并发回一个简短的响应。 Here's the code for the servlet: 这是servlet的代码:

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.*;

/**
 * Servlet implementation class MapleTAServlet
 */
@WebServlet(description = "Receives XML request text containing grade data and returns     response in XML", urlPatterns = { "/MapleTAServlet" })
public class MapleTAServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Log log = LogFactory.getLog(MapleTAServlet.class);

   /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {       
        String strXMLResponse = "<Response><code>";
        String strMessage = "";
        int intCode = 0;
        ServletOutputStream stream = null;
        BufferedInputStream buffer = null;

    try
    {   
        String strContentType = request.getContentType();   

        // Make sure that the incoming request is XML data, otherwise throw up a red flag
        if (strContentType != "text/xml")
        {
            strMessage = "Incorrect MIME type";
        }
        else
        {
            intCode = 1;        
        } // end if

        strXMLResponse += intCode + "</code><message>" + strMessage + "</message></Response>";

        response.setContentType("text/xml");
        response.setContentLength(strXMLResponse.length());

        int intReadBytes = 0;

        stream = response.getOutputStream();

        // Converts the XML string to an input stream of a byte array
        ByteArrayInputStream bs = new ByteArrayInputStream(strXMLResponse.getBytes());
        buffer = new BufferedInputStream(bs);

        while ((intReadBytes = buffer.read()) != -1)
        {
            stream.write(intReadBytes);
        } // end while
    }
    catch (IOException e)
    {
        log.error(e.getMessage());
    }
    catch (Exception e)
    {
        log.error(e.getMessage());
    }
    finally 
    {
        stream.close();
        buffer.close();
    } // end try-catch

    }

}

And here's the client that I'm using to send the request: 这是我用来发送请求的客户端:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;

public class TestClient 
{

   /**
    * @param args
    */
    public static void main(String[] args) 
    {
        BufferedReader inStream = null;

        try
            {
        // Connect to servlet
        URL url = new URL("http://localhost/mapleta/mtaservlet");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Initialize the connection 
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "text/xml");
        //conn.setRequestProperty("Connection", "Keep-Alive");

        conn.connect();

        OutputStream out = conn.getOutputStream();

        inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String strXMLRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request></Request>";
        out.write(strXMLRequest.getBytes());
        out.flush();
        out.close();

        String strServerResponse = "";

        System.out.println("Server says: ");
        while ((strServerResponse = inStream.readLine()) != null)
        {
            System.out.println(strServerResponse);
        } // end while

        inStream.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        } // end try catch
     }
}

The issue I'm having is that when I run the client program, I'm getting the following output: 我遇到的问题是,当我运行客户端程序时,我得到以下输出:

Server says: 
<Response><code>0</code><message>Incorrect MIME type</message></Response>

I've tried calling request.getContentType() and have gotten "text/xml" as the output. 我试过调用request.getContentType()并得到“text / xml”作为输出。 Just trying to figure out why the string isn't matching up. 只是想弄清楚为什么字符串不匹配。

You're comparing strings the wrong way. 你用错误的方式比较字符串。

if (strContentType != "text/xml")

Strings are not primitives , they are objects . 字符串不是原始字母 ,它们是对象 When using != to compare two objects, it will only test if they do not point to the same reference . 当使用!=来比较两个对象时,它只会测试它们是否指向相同的引用 However, you're rather interested in comparing the content of two different string references, not if they point to the same reference. 但是,您对比较两个不同字符串引用的内容非常感兴趣,而不是它们指向相同的引用。

You should then use the equals() method for this: 然后,您应该使用equals()方法

if (!strContentType.equals("text/xml"))

Or, better, to avoid NullPointerException if the Content-Type header is not present (and thus becomes null ): 或者,更好的是,如果Content-Type标头不存在(因此变为null ), NullPointerException避免NullPointerException

if (!"text/xml".equals(strContentType))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM