Java发送POST数据(POST数据集但为空)
我正在尝试使用 java 发送 POST 数据。这是我尝试使用的方法:
public void doSubmit(String url, HashMap<String, String> data) throws Exception {
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
}
以下是我测试它的方法:
HashMap<String, String> data = new HashMap<String, String>();
data.put("img", "someuser");
doSubmit("http://www.blah.com/b.php", data);
在 .php 中进行一些回显测试后,设置了 POST 数据,但 POST 数组为空。为什么?
I'm trying to send POST data using java. Here is the method I'm trying to use:
public void doSubmit(String url, HashMap<String, String> data) throws Exception {
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
}
And here is how I am testing it:
HashMap<String, String> data = new HashMap<String, String>();
data.put("img", "someuser");
doSubmit("http://www.blah.com/b.php", data);
After some echo tests in the .php, the POST data is set, but the POST array is empty. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了完全相同的问题,并在这里找到了解决方案:http://digitallibraryworld.com/?p=189
我正在做的事情和示例所做的主要区别是它生成一个字符串并对其进行 URL 编码 - 我在其中生成 navevaluepairs,然后将它们转换为字符串。
的字节长度。
它也正确地发送了我没有发送
I had exactly the same problem and found the solution here: http://digitallibraryworld.com/?p=189
The main difference between what I was doing and what the example does is it is generating a string and URL encoding it - where I was generating navevaluepairs and then converting them to a string.
It is also sending the length of the bytes correctly
where I was not.
尝试设置
Try setting