使用HttpURLConnection使用表单数据发出POST请求

时间:2018-06-10 11:14:13

标签: java httprequest httpurlconnection

我需要使用HttpURLConnection向外部API发出POST请求。 POST请求涉及正文部分中的表单数据。当使用Postman发出请求时,我可以选择body部分下的表单数据。我如何使用Java代码

实现这一目标
connection = connectionURL.openConnection();

HashMap<String,String> hashmap = new HashMap<String,String>();
hashmap.put("JSONObject","{name:\"Contact from Java\"}");

//Set request method 
((HttpURLConnection) connection).setRequestMethod("POST");

//Set request headers 
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Authorization", "authtoken");

connection.setDoInput(true);
connection.setDoOutput(true);

DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(hashmap.toString());

writer.flush();
writer.close();

已编辑的代码

    connection = connectionURL.openConnection();

    HashMap<String,String> hashmap = new HashMap<String,String>();
    hashmap.put("JSONString","{name:\"Contact from Java\"}");

    //Set request method 
    ((HttpURLConnection) connection).setRequestMethod("POST");

    //Set request headers 
    connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    connection.setRequestProperty("Content-Type", "application/x-www-form-url-encoded;charset=UTF-8");
    connection.setRequestProperty("Authorization", "authtoken");

    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.writeBytes(hashmap.toString());

    writer.flush();
    writer.close();

这是我正在尝试使用Java的请求 This is the request i'm trying to do with Java 这是我的回复

enter image description here

我的错误是什么?提前谢谢

0 个答案:

没有答案
相关问题