在2个Java servlet之间使用HTTP Post

在2个Java servlet之间使用HTTP Post,java,http,servlets,http-post,Java,Http,Servlets,Http Post,我已经设置了一个java servlet,它接受URL中的参数并使其正常工作: public class GetThem extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { double lat=Double.parseDo

我已经设置了一个java servlet,它接受URL中的参数并使其正常工作:

public class GetThem extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException
{
    try {

            double lat=Double.parseDouble(request.getParameter("lat"));
            double lon=Double.parseDouble(request.getParameter("lon"));
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println(lat + " and " + lon);

        } catch (Exception e) {

            e.printStackTrace();
    }
  }       
}
因此,请访问此链接: 将输出:

  "1.0 and 2.0"
我目前正在使用以下代码从另一个java程序调用它:

try{
            URL objectGet = new URL("http://www.example.com:8080/HttpPost/HttpPost?lat=" + Double.toString(dg.getLatDouble()) + "&lon=" + Double.toString(dg.getLonDouble()));
            URLConnection yc = objectGet.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    yc.getInputStream()));
            in = new BufferedReader(
            new InputStreamReader(
            yc.getInputStream()));
            ...
现在我想更改它,这样我就不会使用URL参数将这些数据传递给服务器。我想向这个服务器发送更大的消息。我知道我需要使用HTTPPOST而不是HTTPGET来实现这一点,但我不知道如何做到这一点

我是否需要更改接收数据的服务器端的任何内容?在发布此数据的客户端,我需要做什么

任何帮助都将不胜感激,谢谢。
理想情况下,我希望以JSON格式发送此数据

我认为您应该使用HTTPClient,而不是处理连接和流。检查下面的

这是谷歌中“
JavaHTTPPOST示例
”找到的第一个链接中的示例

try {
    // Construct data
    StringBuilder dataBuilder = new StringBuilder();
    dataBuilder.append(URLEncoder.encode("key1", "UTF-8")).append('=').append(URLEncoder.encode("value1", "UTF-8")).
       append(URLEncoder.encode("key2", "UTF-8")).append('=').append(URLEncoder.encode("value2", "UTF-8"));

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(dataBuilder.toString());
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

谢谢你的回复。是的,也许我在这里发布有点过早。我被ApacheHttpClient和URLConnection弄糊涂了,应该使用哪一个,等等。我也遇到了麻烦,因为HTTPClient的API从V3更改为V4,但我使用的是V3教程。我现在使用URLConnection工作。嗨,谢谢你的回复。我研究了这个(第4版教程),但决定使用URLConnection,因为:1)我只是在学习如何编程和处理连接,这将比使用HTTPClient有更好的理解。2) 我还在开发一款Android应用程序。HTTPClient被谷歌贬低了,他们建议使用URLConnection。我想用同样的方式连接android和其他Servlet,以保持简单。