gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:14:25 25 4
gpt4 key购买 nike

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

 @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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com