我无法解决从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();
}
}
但正如我所见 - 有任何发帖尝试。有人可以帮助我吗?