如何将字符串发送到Http服务器(Java) [英] How To Send a String to a Http Server (Java)
本文介绍了如何将字符串发送到Http服务器(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的http服务器,我需要在 Stream
上发送 String
。但是,String包含空格,我知道如何在 Stream
上从客户端编写它。如何在服务器
一侧收到它?
I have a simple http server and I need to send a String
over a Stream
. However, the String contains spaces and I know how to write it from client on the Stream
. How can I receive it on the Server
side?
static class InsertPostHandler implements HttpHandler {
public void handle(final HttpExchange HE) throws IOException {
Thread thread = new Thread(new Runnable() {
final HttpExchange t = HE;
@Override
public void run() {
Statement stmt = null;
// add the required response header for a PDF file
String Request =(t.getRequestURI().toString()
.split("\\/@@postssystem/"))[1];
System.out.println(Request);
if(Request.equals("createpost")){
Headers h = t.getResponseHeaders();
h.add("Content-Type", "Image");
h.add("Cache-Control","must-revalidate");
//Here I Need To Receive A String
try {
t.sendResponseHeaders(200,1);
} catch (IOException e) {
e.printStackTrace();
}
推荐答案
您可以尝试以下代码:
You can try following code:
try {
String toSend = "message";
String urlParameters = "message=" + toSend;
String request = "http://IP:PORT/Project/message.html";
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);
int code = connection.getResponseCode();
System.out.println(code);
wr.flush();
wr.close();
connection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
您可以指定 IP
和端口
您的服务器。并且可以将任何数据作为参数发送。
You can specify IP
and port
of your server. And can send any data as a parameter.
这篇关于如何将字符串发送到Http服务器(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文