简体   繁体   English

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

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

在邮递员中请求

How in java, can I send a request with x-www-form-urlencoded header .如何在 java 中发送带有x-www-form-urlencoded header的请求。 I don't understand how to send a body with a key-value, like in the above screenshot.我不明白如何发送带有键值的正文,如上面的屏幕截图所示。

I have tried this code:我试过这段代码:

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

But in the response, I don't receive the correct data.但是在响应中,我没有收到正确的数据。

As you set application/x-www-form-urlencoded as content type so data sent must be like this format.当您将application/x-www-form-urlencoded为内容类型时,发送的数据必须是这种格式。

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

For HttpEntity , the below answer works对于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 );

For reference: How to POST form data with Spring RestTemplate?供参考: 如何使用 Spring RestTemplate POST 表单数据?

Use Java 11 HttpClient使用 Java 11 HttpClient

The HTTP Client was added in Java 11. It can be used to request HTTP resources over the.network. HTTP客户端是在Java 11中新增的,可以用来通过.network请求HTTP资源。 It supports HTTP/1.1 and HTTP/2, both synchronous and asynchronous programming models, handles request and response bodies as reactive-streams, and follows the familiar builder pattern.它支持同步和异步编程模型 HTTP/1.1 和 HTTP/2,将请求和响应主体作为反应流处理,并遵循熟悉的构建器模式。

https://openjdk.java.net/groups.net/httpclient/intro.html https://openjdk.java.net/groups.net/httpclient/intro.html

HttpClient client = HttpClient.newHttpClient();;
HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI(targetUrl))
        .POST(urlParameters)
        .headers("Content-Type", "application/x-www-form-urlencoded")
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
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();
                }

Building off of Navoneel's answer , I like to use StreamEx's EntryStream .基于Navoneel 的回答,我喜欢使用StreamEx 的EntryStream

Here is Naveoneel's method re-written.这是重写的 Naveoneel 方法。

private String getDataString(HashMap<String, String> params)
{
   return EntryStream.
      of(data).
      mapKeys(key -> URLEncoder.encode(key, StandardCharsets.UTF_8)).        // Encode the keys
      mapValues(value -> URLEncoder.encode(value, StandardCharsets.UTF_8)).  // Encode the values
      join("=").                                                             // Create a key=value
      joining("&");                                                          // Assemble into key1=value1&key2=value2...
}

Problem with the Response!响应有问题!

I had a similar issue when I was sending the request of media type application/x-www-form-urlencoded from Postman I was receiving a correct response.当我从 Postman 发送媒体类型application/x-www-form-urlencoded的请求时,我遇到了类似的问题,我收到了正确的回复。

However, when sending the request using code, I was receiving jargon somewhat like:但是,在使用代码发送请求时,我收到的行话有点像:

�-�YO�`:ur���g�
.n��l���u)�i�h3J%Gl�?����k  


What I tried:我尝试了什么:

Out of frustration for multiple days tried all the possible solutions from changing character sets to changing header values to code changes and whatnot.出于沮丧,连续几天尝试了所有可能的解决方案,从更改字符集到更改 header 值再到代码更改等等。


Solution lies in Postman.解决方案在于Postman。

代码生成

Select Java-OkHttp Select Java-OkHttp

在此处输入图像描述

Copy the code and paste it into IDE.复制代码并将其粘贴到 IDE。

That's it.就是这样。

Reference for HttpOk: https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html HttpOk参考: https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Android批注和RestTemplate在POST请求的正文中发送x-www-form-urlencoded - How to send x-www-form-urlencoded in a body of POST request using android annotations and resttemplate 如何使用 webclient 发布正文 x-www-form-urlencoded? - how to post body x-www-form-urlencoded using webclient? 如何以 application/x-www-form-urlencoded 在 restTemplate 中发送正文 - How to send body in restTemplate as application/x-www-form-urlencoded FeignClient 使用 application/x-www-form-urlencoded 正文创建 POST - FeignClient create POST with application/x-www-form-urlencoded body 使用x-www-form-urlencoded的Jersey客户端发布请求失败 - Jersey client Post Request with x-www-form-urlencoded Fails Spring - 使用 x-www-form-urlencoded 错误编码 POST 请求 - Spring - wrong encoding POST request with x-www-form-urlencoded 如何在 HTTPURLConnection 中以 application/x-www-form-urlencoded 格式向 POST 调用添加正文 - How to add a body to POST call in HTTPURLConnection in application/x-www-form-urlencoded format POST x-www-form-urlencoded - POST x-www-form-urlencoded 未找到Form&application / x-www-form-urlencoded的Body Writer - Body Writer not found for Form & application/x-www-form-urlencoded feign application/x-www-form-urlencoded 类型请求的服务器端缺少请求正文 - Request body is missing in the server end for feign application/x-www-form-urlencoded type request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM