Besides receiving information from a remote server, a mobile app might need to send information as well. The following example will contain two buttons: one for sending a POST request to a test server5 and one for receiving the transmission protocol. The server URL as well as the message to be transmitted are defined as constants:
const string url = "http://posttestserver.com/post.php";
const string message = "Xamarin.Forms!";
The server responses are written into two labels. We use a slightly smaller font size to fit everything on one screen.
var postResponse = new Label{ FontSize = 11 };
var getResponse = new Label{ FontSize = 11 };
The postButton will create a new StringContent with the previously defined message. Using a new HttpClient the content is sent to the server. Although POST is mainly for sending data, the server returns a response as well. We could use the status code for handling different errors. But here we simply write the response message to the postResponse label.
var postButton = new Button {
Text = string.Format("Post \"{0}\"", message),
Command = new Command(async o => {
var content = new StringContent(message);
using (var client = new HttpClient()) {
var result = await client.PostAsync(url, content);
postResponse.Text = await result.Content.ReadAsStringAsync();
}
}),
};
The getButton uses the previous response message to extract the URL of the transmission protocol. The exact format depends on the specific server. But usually POST requests are answered with a meaningful status code and possibly a URL, where the client can find the result of the respective operation. Finally, the result is written to the getResponse label.
var getButton = new Button {
Text = "Get",
Command = new Command(async o => {
using (var client = new HttpClient())
getResponse.Text = await client.GetStringAsync(postResponse.Text.Split()[8]);
}),
};
Both labels and the two buttons are added to the MainPage using a StackLayout.
MainPage = new ContentPage {
Padding = new Thickness(10, Device.OS == TargetPlatform.iOS ? 20 : 0, 10, 0),
Content = new StackLayout {
Children = {
postButton,
postResponse,
getButton,
getResponse,
},
},
};
Note that this is a rather technical example app. Usually these POST and GET requests are performed asynchronously in the background and not visible to the user.