0

我有一个服务器和一个客户端,
在服务器端我有这个处理程序

 @Override
 public void handleHttpRequest(HttpRequest httpRequest,
 HttpResponse httpResponse,
 HttpControl httpControl) throws Exception {
 // ..
 }

问题是如何从客户端发送数据以及服务器端的什么方法将包含发送的数据?

如果有更好的使用 webbit 进行通信的方法,也将受到欢迎。

4

2 回答 2

1

在 POST 请求中,参数作为请求正文发送,位于请求头之后。

要使用 HttpURLConnection 进行 POST,您需要在打开连接后将参数写入连接。

这段代码应该让你开始:

String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();

或者,您可以使用此助手发送 POST 请求并获取请求

    public static String getStringContent(String uri, String postData, 
    HashMap<String, String> headers) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost();
    request.setURI(new URI(uri));
    request.setEntity(new StringEntity(postData));
    for(Entry<String, String> s : headers.entrySet())
    {
        request.setHeader(s.getKey(), s.getValue());
    }
    HttpResponse response = client.execute(request);

    InputStream ips  = response.getEntity().getContent();
    BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
    if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
    {
        throw new Exception(response.getStatusLine().getReasonPhrase());
    }
    StringBuilder sb = new StringBuilder();
    String s;
    while(true )
    {
        s = buf.readLine();
        if(s==null || s.length()==0)
            break;
        sb.append(s);

    }
    buf.close();
    ips.close();
    return sb.toString();
   }
于 2013-08-15T11:21:06.747 回答
0

通常会扩展 HttpServlet 并覆盖 doGet。

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html

我不熟悉 webbit,但我不认为它是一个 Servlet 网络服务器。它提到它提供静态页面。

于 2013-08-15T08:43:30.083 回答