0

我已经设置了一个 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();
    }
  }       
}

所以访问这个链接: http://www.example.com:8080/HttpPost/HttpPost?lat=1&lon=2会输出:

  "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 参数将此数据传递给服务器。我想向该服务器发送更大的消息。我知道我需要使用 http post 而不是 http get 来实现这一点,但不知道该怎么做。

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

任何帮助将不胜感激。理想情况下,我想以 JSON 格式发送这些数据。

4

2 回答 2

0

我认为您应该使用 HTTPClient 而不是处理连接和流。检查http://hc.apache.org/httpclient-3.x/tutorial.html

于 2012-07-20T05:17:11.777 回答
0

下面是“ java HTTP POST example”在谷歌中找到的第一个链接的示例。

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) {
}
于 2012-07-20T05:20:12.633 回答