【问题标题】:How to send post request with x-www-form-urlencoded body如何使用 x-www-form-urlencoded 正文发送发布请求
【发布时间】:2017-03-27 06:32:37
【问题描述】:

如何在 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 ();

但在响应中,我没有收到正确的数据。

【问题讨论】:

  • 您是否捕获了使用 Wireshark 之类的工具发送的内容以确认该标头实际上不存在?

标签: java


【解决方案1】:

由于您将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 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 );
}

或者您可以创建一个通用方法来构建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();
}

【讨论】:

  • 嗨玛丽!你做了什么让它发挥作用?我尝试了相同的方法(以及 10 个小时的许多不同的东西),但它不起作用:(
  • 终于找到了解决办法:stackoverflow.com/questions/39937240/…
  • 有人可以向我解释"charset", "utf-8" 部分吗?我认为这可能是错误的,因为它应该是 Content-Type 标头的一部分,而不是本身的标头。
  • 我如何使用改造任何想法以这种方式发送#Navoneel Talukdar
【解决方案2】:

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

供参考: How to POST form data with Spring RestTemplate?

【讨论】:

    【解决方案3】:
    string urlParameters = "param1=value1&param2=value2";
    string _endPointName = "your url post api";
    
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
    
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Method = "POST";
    httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
    
    System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                                                      (se, cert, chain, sslerror) =>
                                                      {
                                                          return true;
                                                      };
    
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        streamWriter.Write(urlParameters);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                    }
    

    【讨论】:

    • 为您的答案添加一些上下文,并限制自己发布确切的代码 sn-p 例如。在你的情况下,httpWebRequest.Headers["ContentType"] 所以更容易理解
    猜你喜欢
    • 2018-12-25
    • 2021-01-19
    • 2018-07-30
    • 1970-01-01
    • 2021-03-14
    • 2023-04-10
    相关资源
    最近更新 更多