How to send post request with x-www-form-urlencoded body

前端 未结 2 1341
旧时难觅i
旧时难觅i 2020-11-29 03:01

\"Request

How in java, can I send a request with x-www-form-urlencoded header. I don\

相关标签:
2条回答
  • 2020-11-29 03:19

    As you set application/x-www-form-urlencoded as content type so data sent must be like this format.

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

    Sending part now is quite straightforward.

    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 );
    }
    

    Or you can create a generic method to build key value pattern which is required for 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();
    }
    
    0 讨论(0)
  • 2020-11-29 03:19

    For HttpEntity, the below answer works

    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 );
    

    For reference: How to POST form data with Spring RestTemplate?

    0 讨论(0)
提交回复
热议问题