AppEngine: как увидеть содержимое из запроса POST - PullRequest
1 голос
/ 24 января 2011

Я отправляю запрос POST на мой сервер AppEngine. HttpServletRequest говорит мне:

POST /connexionDeconnexion HTTP/1.1
User-Agent: Java/1.6.0_20
Host: localhost:8888
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 25

Я отправил миру «HelloHelloHelloHelloHello», который является правильным в соответствии с длиной содержимого. Однако я не знаю, как его восстановить. Ты можешь мне объяснить?

Ответы [ 2 ]

4 голосов
/ 24 января 2011

Как сказал Джигар, вы можете использовать request.getParameter().Это работает, если вы действительно отправляете форму или указываете параметр в качестве аргумента URL (http://myhost/mypath?myparam=myvalue).

Если вы отправляете свои данные в виде тела POST, вы должны прочитать их из тела, то есть получить поток ввода, вызвав request.getInputStream(), а затемчитать из этого потока.

1 голос
/ 24 января 2011

Вы должны указать имя и значение параметра, а затем извлечь его из объекта httpRequest.

request.getParameter("paramName");

Обновление

на стороне клиента

String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
    OutputStream output = connection.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

    // Send normal param.
    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"param\"");
    writer.println("Content-Type: text/plain; charset=" + charset);
    writer.println();
    writer.println(param);

    // Send text file.
    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"");
    writer.println("Content-Type: text/plain; charset=" + charset);
    writer.println();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(textFile), charset));
        for (String line; (line = reader.readLine()) != null;) {
            writer.println(line);
        }
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    }

    // Send binary file.
    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"");
    writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName());
    writer.println("Content-Transfer-Encoding: binary");
    writer.println();
    InputStream input = null;
    try {
        input = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
        output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
    } finally {
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
    writer.println(); // Important! Indicates end of binary boundary.

    // End of multipart/form-data.
    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();
}

Также см.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...