gpt4 book ai didi

java - 通过 java 将查询字符串直接发布到 httpHandler

转载 作者:太空宇宙 更新时间:2023-11-04 07:57:47 26 4
gpt4 key购买 nike

我有一个 http 处理程序位于:

http://localhost:8118/log.srv

当我将此网址粘贴到 IE 上时,效果很好。

http://localhost:8118/log.srv?action=likearticle&noname=989858&ladoi=cutymaraton

http 处理程序获取数据。

但是当我使用java程序发布数据时,没有发生错误,但是http处理程序没有获取任何数据。我的java程序:

public static void main(String[] args) {
try {
for(int i=1; i<1000; i++){
URL url= new URL("http://localhost:8118/log.srv");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String data = "action=likearticle&noname=989858&ladoi=cutymaraton"+i;
System.out.println(data);
writer.write(data);
writer.flush();
}

System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}

我使用另一个代码:

String urlParameters = "action=likearticle&noname=989858&ladoi=cutymaraton";
String request = "http://localhost:8118/log.srv";
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();

没有错误,但发送数据失败。告诉我为什么?有什么解决办法吗?

最佳答案

您可以使用 more friendly API,像这样:

PostMethod post = new PostMethod("http://localhost:8118/log.srv");
post.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
NameValuePair[] data = {
new NameValuePair("action", "likearticle"),
new NameValuePair("noname", "989858"),
new NameValuePair("ladoi", "cutymaraton")
};
post.setRequestBody(data);

HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);

InputStream in = post.getResponseBodyAsStream();
// handle response.

关于java - 通过 java 将查询字符串直接发布到 httpHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342068/

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