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

mar*_*ari 37 java

邮递员要求

如何在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 ();
Run Code Online (Sandbox Code Playgroud)

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

Nav*_*dar 47

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

String urlParameters  = "param1=data1&param2=data2&param3=data3";
Run Code Online (Sandbox Code Playgroud)

现在发送部分非常简单.

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
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 );
}
Run Code Online (Sandbox Code Playgroud)

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

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 最后我找到了解决方案:http://stackoverflow.com/questions/39937240/android-post-request-not-working (2认同)

Nut*_*tan 17

因为HttpEntity,以下答案有效

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "first.last@example.com");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
Run Code Online (Sandbox Code Playgroud)

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