检查HTTP POST请求的Content-Type到Java servlet

3
我编写了一个简单的Servlet,它接受HTTP POST请求并发送一个简短的响应。以下是该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

    }

}

这是我用来发送请求的客户端:

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
     }
}

我是一个能翻译文本的助手。
我遇到的问题是,当我运行客户端程序时,会得到以下输出结果:
Server says: 
<Response><code>0</code><message>Incorrect MIME type</message></Response>

我尝试调用 request.getContentType(),输出结果为 "text/xml"。只是想弄清楚为什么这个字符串不匹配。
1个回答

10

您正在错误地比较字符串。

if (strContentType != "text/xml")

字符串不是基本类型, 它们是对象。当使用!=比较两个对象时,它只会测试它们是否指向相同的引用。然而,您更关心比较两个不同字符串引用的内容,而不是它们是否指向相同的引用。

您应该使用equals()方法

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

或者更好的方法是,如果Content-Type头不存在(因此变为null),则避免NullPointerException

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

7
这是确定HttpServletRequest的contenttype的正确方法吗?我对它不是很满意,因为当您寻找精确的字符串匹配时,“text/xml”与“text/xml;charset=UTF-8”不同,而这与“text/xml; charset=UTF-8”又不同,这与“application/xml”也不同。所以是否有一种干净的方式仅区分例如xml请求和表单请求?因此,无需手动覆盖表示不同请求类型的各种字符串变体。 - tObi
我的doPost方法出现了CAST违规,因为没有在内部调用getContentType方法...我能不能这样简单地使用它呢?尝试以下代码: try { String msg=""; String strContentType = req.getContentType(); if (!"text/xml".equals(strContentType)) msg="无效的MIME类型"; }catch(Exception e) { e.printStackTrace(); } - not-a-bug
如果 getContentType 返回 null,它会如何表现。 - not-a-bug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接