Java HTTP webbit如何发送/接收消息

时间:2013-08-15 08:07:34

标签: java http client-server

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

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

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

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

2 个答案:

答案 0 :(得分: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();
   }

答案 1 :(得分:0)

通常会扩展HttpServlet并覆盖doGet。

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

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