如何使用x-www-form-urlencoded正文发送post请求

邮递员要求

如何在java中,我可以使用x-www-form-urlencoded header发送请求。 我不明白如何发送带有键值的正文,如上面的截图所示。

我试过这段代码:

 String urlParameters = cafedra_name+ data_to_send; URL url; HttpURLConnection connection = null; try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches (false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream ( connection.getOutputStream ()); wr.writeBytes (urlParameters); wr.flush (); wr.close (); 

但在回复中,我没有收到正确的数据。

当您将application/x-www-form-urlencoded为内容类型时,所以发送的数据必须与此格式相同。

 String urlParameters = "param1=data1&param2=data2&param3=data3"; 

现在发送部分非常简单。

 byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; String request = ""; URL url = new URL( request ); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength )); conn.setUseCaches(false); try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write( postData ); } 

或者,您可以创建一个通用方法来构建application/x-www-form-urlencoded所需的键值模式。

 private String getDataString(HashMap params) throws UnsupportedEncodingException{ StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } 

对于HttpEntity ,以下答案有效

 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap map= new LinkedMultiValueMap(); map.add("email", "first.last@example.com"); HttpEntity> request = new HttpEntity>(map, headers); ResponseEntity response = restTemplate.postForEntity( url, request , String.class ); 

供参考: 如何使用Spring RestTemplate发布表单数据?