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

标签 java http client-server

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

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

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

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

最佳答案

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

要使用 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();
   }

关于Java HTTP webbit如何发送/接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18248608/

相关文章:

java:将字符串转换为包含每个字符的十六进制数的字符串

ruby-on-rails - 那些具有 "iframe=true&width=80%&height=80%"查询参数的请求怎么了?

http - 为什么服务器不设置 HTTP 响应代码?

ssl - 带 SSL/TLS 的 PHP 套接字 - 无法使用合适的共享密码

tcp 应用程序退出总是会发送 FIN 吗?

java - 如何从客户端服务器程序中的服务器控制台获取输入

java - 在 DAO 模式中使用泛型

java - 覆盖 gwt 中的默认小部件类名称

javascript - 无法从下拉列表中选择值

c# - 如何识别 HttpModule 中的 UNC Access