java - 检查对 Java servlet 的 HTTP POST 请求的内容类型

标签 java httpurlconnection

我编写了一个简单的 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”作为输出。只是想弄清楚为什么字符串不匹配。

最佳答案

您以错误的方式比较字符串。

if (strContentType != "text/xml")

Strings不是 primitives , 他们是 objects .当使用 != 比较两个对象时,它只会测试它们是否指向相同的 reference。但是,您更感兴趣的是比较两个不同字符串引用的内容,而不是它们是否指向同一引用。

然后你应该使用 the equals() method为此:

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

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

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

关于java - 检查对 Java servlet 的 HTTP POST 请求的内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7663457/

相关文章:

java - JOOQ 多个配置文件

java - 当我使用 computeIfAbsent 计算斐波那契数时,hashmap size() 返回不正确的值

java - 从 HttpClient 更新到 HttpURLConnection

android - 即使连接超时和读取超时设置为默认值(无限),接收请求超时?

安卓应用下载文件

java - 是否可以在替换函数中使用 OR 条件/运算符?

java - 如何使用 Spark 并行化列表列表?

java - Spring webflux : how to publish event from sync call for async processing?

Android HttpsURLConnection on 2.3.4 OutOfMemoryError while uploading Large File (byte[] in memory)

java - 如何使用 HttpURLConnection 在 Java 中设置下载器代理的名称?