我正在尝试使用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中执行一些echo测试后,post数据被设置,但是post数组是空的。为什么?

最佳答案

尝试设置

connection.setRequestProperty("Accept-Charset", 'UTF-8');
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

关于java - Java发送POST数据(POST数据集但为空),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6922303/

10-13 07:16