Urlencode windows forms application

Отправка данных HTML-формы в веб-API ASP.NET: данные Form-UrlEncoded Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data

Часть 1. форма-UrlEncoded данных Part 1: Form-urlencoded Data

В этой статье показано, как опубликовать данные формы-UrlEncoded в контроллере веб-API. This article shows how to post form-urlencoded data to a Web API controller.

Общие сведения о HTML-формах Overview of HTML Forms

Для отправки данных на сервер в HTML-формах используется либо GET, либо POST. HTML forms use either GET or POST to send data to the server. Атрибут method элемента Form предоставляет метод HTTP: The method attribute of the form element gives the HTTP method:

Обратите внимание, что атрибут Action в форме является универсальным кодом ресурса (URI) действия контроллера. Notice that the action attribute on the form is the URI of our controller action. Ниже приведена форма с некоторыми значениями, введенными в: Here is the form with some values entered in:

Когда пользователь нажимает кнопку Отправить, браузер отправляет HTTP-запрос, аналогичный следующему: When the user clicks Submit, the browser sends an HTTP request similar to the following:

Обратите внимание, что текст запроса содержит данные формы, отформатированные как пары «имя-значение». Notice that the request body contains the form data, formatted as name/value pairs. Веб-API автоматически преобразует пары «имя-значение» в экземпляр класса Update . Web API automatically converts the name/value pairs into an instance of the Update class.

Отправка данных формы через AJAX Sending Form Data via AJAX

Когда пользователь отправляет форму, браузер переходит от текущей страницы и отображает текст ответного сообщения. When a user submits a form, the browser navigates away from the current page and renders the body of the response message. Это нормально, когда ответ является HTML-страницей. That’s OK when the response is an HTML page. Однако в веб-API текст ответа обычно либо пуст, либо содержит структурированные данные, такие как JSON. With a web API, however, the response body is usually either empty or contains structured data, such as JSON. В этом случае имеет смысл отправить данные формы с помощью запроса AJAX, чтобы страница могла обработать ответ. In that case, it makes more sense to send the form data using an AJAX request, so that the page can process the response.

В следующем коде показано, как отправлять данные формы с помощью jQuery. The following code shows how to post form data using jQuery.

Функция отправки jQuery заменяет действие формы новой функцией. The jQuery submit function replaces the form action with a new function. Это переопределяет поведение по умолчанию кнопки Отправить. This overrides the default behavior of the Submit button. Функция Serialize сериализует данные формы в пары «имя-значение». The serialize function serializes the form data into name/value pairs. Чтобы отправить данные формы на сервер, вызовите $.post() . To send the form data to the server, call $.post() .

Читайте также:  Протокол доступа windows linux

По завершении запроса обработчик .success() или .error() отображает соответствующее сообщение пользователю. When the request completes, the .success() or .error() handler displays an appropriate message to the user.

Отправка простых типов Sending Simple Types

В предыдущих разделах мы отправили сложный тип, который веб-API десериализует в экземпляр класса Model. In the previous sections, we sent a complex type, which Web API deserialized to an instance of a model class. Можно также отправить простые типы, например строку. You can also send simple types, such as a string.

Перед отправкой простого типа рекомендуется обернуть значение в сложный тип. Before sending a simple type, consider wrapping the value in a complex type instead. Это дает преимущества проверки модели на стороне сервера и упрощает расширение модели при необходимости. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

Основные шаги для отправки простого типа одинаковы, но есть два незначительных различия. The basic steps to send a simple type are the same, but there are two subtle differences. Сначала в контроллере необходимо снабдить имя параметра атрибутом FromBody . First, in the controller, you must decorate the parameter name with the FromBody attribute.

По умолчанию веб-API пытается получить простые типы из универсального кода ресурса (URI) запроса. By default, Web API tries to get simple types from the request URI. Атрибут FromBody сообщает веб-API о необходимости считывания значения из текста запроса. The FromBody attribute tells Web API to read the value from the request body.

Веб-API считывает текст ответа не более одного раза, поэтому в тексте запроса может быть только один параметр действия. Web API reads the response body at most once, so only one parameter of an action can come from the request body. Если необходимо получить несколько значений из текста запроса, определите сложный тип. If you need to get multiple values from the request body, define a complex type.

Во вторых, клиенту необходимо отправить значение в следующем формате: Second, the client needs to send the value with the following format:

В частности, часть имени пары «имя-значение» для простого типа должна быть пустой. Specifically, the name portion of the name/value pair must be empty for a simple type. Не все браузеры поддерживают это для HTML-форм, но этот формат создается в скрипте следующим образом: Not all browsers support this for HTML forms, but you create this format in script as follows:

Ниже приведен пример формы. Here is an example form:

И вот сценарий для отправки значения формы. And here is the script to submit the form value. Единственное отличие от предыдущего скрипта — это аргумент, передаваемый в функцию POST . The only difference from the previous script is the argument passed into the post function.

Один и тот же подход можно использовать для отправки массива простых типов: You can use the same approach to send an array of simple types:

Handling URL Encoded Form Data in Spring REST

Last modified: December 31, 2020

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

If you have a few years of experience in the Java ecosystem, and you’re interested in sharing that experience with the community (and getting paid for your work of course), have a look at the «Write for Us» page. Cheers, Eugen

1. Overview

For an end-user, the process of form submission is convenient, and to some extent, equivalent to just entering data and clicking on a submit button. However, from an engineering perspective, it takes an encoding mechanism to reliably send and receive this data from the client-side to the server-side for back-end processing.

Читайте также:  Woe usb linux manjaro

For the scope of this tutorial, we’ll focus on creating a form that sends its data as application/x-www-form-urlencoded content type in a Spring web application.

2. Form Data Encoding

The most commonly used HTTP method for form submissions is POST. However, for idempotent form submissions, we can also use the HTTP GET method. And, the way to specify the method is through the form’s method attribute.

For forms that use the GET method, the entire form data is sent as part of the query string. But, if we’re using the POST method, then its data is sent as part of the body of the HTTP request.

Moreover, in the latter case, we can also specify the encoding of data with the form’s enctype attribute, which can take two values, namely application/x-www-form-urlencoded and multipart/form-data.

2.1. Media Type application/x-www-form-urlencoded

HTML forms have a default value of application/x-www-form-urlencoded for the enctype attribute as this takes care of the basic use cases where data is entirely text. Nevertheless, if our use case involves supporting file data, then we’ll have to override it with a value of multipart/form-data.

Essentially, it sends the form data as key-value pairs separated by an ampersand (&) character. Also, the respective key and value are separated with the equals sign (=). Further, all reserved and non-alphanumeric characters are encoded using percent-encoding.

3. Form Submission in Browser

Now that we have our basics covered, let’s go ahead and see how we can handle URL encoded form data for a simple use case of feedback submission in a Spring web app.

3.1. Domain Model

For our feedback form, we need to capture the email identifier of the submitter along with the comment. So, let’s create our domain model in a Feedback class:

3.2. Create Form

To use a simple HTML template to create our dynamic web form, we’ll need to configure Thymeleaf in our project. After this, we’re ready to add a GET endpoint /feedback that will serve the feedback view for the form:

Note that we’re using feedback as a model attribute to capture the user input. Next, let’s create the feedback view in the feedback.html template:

Of course, we don’t need to explicitly specify the enctype attribute as it’ll pick the default value of application/x-www-form-urlencoded.

3.3. PRG Flow

As we’re accepting user input through the browser feedback form, we must implement the POST/REDIRECT/GET (PRG) submission workflow to avoid duplicate submissions.

First, let’s implement the POST endpoint /web/feedback that’ll act as the action handler for the feedback form:

Next, we can implement the redirect endpoint /feedback/success that serves a GET request:

To validate the functionality of form submission workflow in a browser, let’s visit localhost:8080/feedback:

Finally, we can also inspect that form data is being sent in the URL encoded form:

4. Non-Browser Requests

At times, we might not have a browser-based HTTP client. Instead, our client could be a utility such as cURL or Postman. In such a case, we don’t need the HTML web form. Instead, we can implement a /feedback endpoint that serves the POST request:

In the absence of the HTML form in our data flow, we don’t necessarily need to implement the PRG pattern. However, we must specify that the resource accepts APPLICATION_FORM_URLENCODED_VALUE media type.

Читайте также:  Что будет если прервать настройку обновлений windows

Finally, we can test it with a cURL request:

4.1. FormHttpMessageConverter Basics

An HTTP request that sends application/x-www-form-urlencoded data must specify this in the Content-Type header. Internally, Spring uses the FormHttpMessageConverter class to read this data and bind it with the method parameter.

In cases where our method parameter is of a type MultiValueMap, we can use either the @RequestParam or @RequestBody annotation to bind it appropriately with the body of the HTTP request. That’s because the Servlet API combines the query parameters and form data into a single map called parameters, and that includes automatic parsing of the request body:

However, for a method parameter of type other than MultiValueMap, such as our Feedback domain object, we must use only the @RequestBody annotation.

5. Conclusion

In this tutorial, we briefly learned about the encoding of form data in web forms. We also explored how to handle URL encoded data for browser and non-browser HTTP requests by implementing a feedback form in a Spring Boot web app.

As always, the complete source code for the tutorial is available over on GitHub.

C# application/x-www-form-urlencoded OAuth and HTTP REST requests using HttpClient

So I’m trying to put together some very simple and elegant code samples to help people use my API. The latest language I’m tackling is C#.

I think the IETF OAuth2.0 standard I read implies the HTTP request Content-Type must be «application/x-www-form-urlencoded». The Django API server I have, currently seems to only support this Content-Type (for the OAuth resource). The other languages POST content this way by default!

After extensive research and several experiments I am wondering if I have missed something fundamental. Surely there would be a helpful library OR technique to create the . urlencoded string OR at least someone else must have run into this.

I will outline some of the best solution I have so far bellow, but it just seems wrong.

Also from a bunch of internet browsing I figured I would use the HttpClient library. I like the fact that it uses the async model, which perhaps will be more useful for any developers using WPF or XAML or Windows 8 apps. It also works well for Consoles and Forms.

I use the Newtonsoft Json.Net library for serialization. First of all I create a POCO of the authorization strings. Then I serialize it to JSON, then to key/value pairs, then iterate through the key/value pairs catenating with the required ‘=’ and ‘&’ chars, then UTF-8, then escape the spaces etc.

Other options I could think of were.

Reflection, however digging into reflection in a code sample seems a bit manic.

It turns out that other than the OAuth setup, the rest of the API supports JSON type POSTs. So I guess I could write a function to walk through the oAuthConfig model and catenate a string, since that POCO model is unlikely to change and is the only model which requires urlEncoding that I can anticipate. That would save us from the slightly confusing use of the Dictionary. The use of the dictionary and then iterating is more generic, however perhaps a bit OTT.

I figure most of the time people will be using JSON, so showing how that might happen is useful.

In general it seems quite hard to serialize a POCO model to a string and/or to a urlEncoded string.

  • does OAuth mandate urlencoded, could you convert server-side?
  • is HttpClient the best choice, does async matter?
  • is there a better simpler way to serialize a POCO to . form-urlencoded?

Thanks for any useful comments you may have.

Оцените статью