从servlet到另一台服务器的POST数据不起作用

时间:2014-05-30 14:31:50

标签: java servlets post

我无法解决从servlet向其他服务器发送POST数据的问题。这是我的代码:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class DemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("Hello");

    URL url = new URL("http://myserveraddress.com/file.php");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Length", "" + stringBuilder.length());

    OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
    outputWriter.write(stringBuilder.toString());
    outputWriter.flush();
    outputWriter.close();
}

}

但正如我所见 - 有任何发帖尝试。有人可以帮助我吗?

0 个答案:

没有答案