我需要使用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();
我的错误是什么?提前谢谢