Send a Multipart Form POST request with parameters

This code can be used in order to send a Multipart Form as part of a POST request with parameters. This kind of POST request will usually be used to send Files, but there some cases where you will need this without sending any files. Next paragraphs will explain the code.

First we create the HttpClient object and the POST method object. (lines 1-2)
Then we create a MutipartEntity. This type of entity enables us to send both string parameters and files in the same request. We then assign the MultipartEntity to be the PostMethod’s entity. (line 4-5)

Now we create a StringBody. We use StringBody to pass regular string parameters (very much the same as a regular POST request, only this is the way it done for a Multipart request). We add the StringBody to the MultipartEntity.(lines 7-8)
We perform this step twice, once for each of the parameters (firstName and lastName).

The rest of the code is pretty straight forward. We execute the request, and print the response status code, and content.


HttpClient client = new HttpClient();
HttpPost postMethod = new HttpPost(new Uri("http://www.w3schools.com/asp/demo_simpleform.asp"));

MultipartEntity multipartEntity = new MultipartEntity();
postMethod.Entity = multipartEntity;

StringBody stringBody = new StringBody(Encoding.UTF8, "firstName", "brian");
multipartEntity.AddBody(stringBody);

StringBody stringBody2 = new StringBody(Encoding.UTF8, "lastName", "star");
multipartEntity.AddBody(stringBody2);
            
HttpResponse response = client.Execute(postMethod);

Console.WriteLine("Response Code: " + response.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));

For this to work you will need the following using directives:

using CodeScales.Http;
using CodeScales.Http.Methods;
using CodeScales.Http.Entity;
using CodeScales.Http.Entity.Mime;
using CodeScales.Http.Common;

 


Send a POST request with files

This is one of the coolest features of HttpClient! See how easy it is to send files as part of the POST request:
First we create the HttpClient object and the POST method object. (lines 1-2)
Then we create a MutipartEntity. This type of entity enables us to send both string parameters and files in the same request. We then assign the MultipartEntity to be the PostMethod’s entity. (line 4-5)

Now we create a StringBody. We use StringBody to pass regular string parameters (very much the same as a regular POST request, only this is the way it done for a Multipart request). We add the StringBody to the MultipartEntity.(lines 7-8)

Here comes the interesting part: We create a FileBody object. This is used to send files as part of a MutipartPost request. We also need a FileInfo object to point to the file we want to send. The FileInfo needs the actual name and location of the file we want to send. The FileBody objects gets the pointer to the file as a parameter (fileInfo), and also we can decide what is the name of the file parameter, and what will be the file-name that will be passed to the server. We than add the FileBody to the MultipartEntity. (lines 10-12)

The rest of the code is pretty straight forward. We execute the request, and print the response status code, and content.


HttpClient client = new HttpClient();
HttpPost postMethod = new HttpPost(new Uri("http://www.w3schools.com/asp/demo_simpleform.asp"));

MultipartEntity multipartEntity = new MultipartEntity();
postMethod.Entity = multipartEntity;

StringBody stringBody = new StringBody(Encoding.UTF8, "firstName", "brian");
multipartEntity.AddBody(stringBody);

FileInfo fileInfo = new FileInfo(@"c:\temp\example.jpg");
FileBody fileBody = new FileBody("file1", "example.jpg", fileInfo);
multipartEntity.AddBody(fileBody);

HttpResponse response = client.Execute(postMethod);

Console.WriteLine("Response Code: " + response.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));

For this to work you will need the following using directives:

using System.IO;
using CodeScales.Http;
using CodeScales.Http.Methods;
using CodeScales.Http.Entity;
using CodeScales.Http.Entity.Mime;
using CodeScales.Http.Common;

 


Send a basic POST request

This example demonstrates how to send a POST request using the HttpClient library.

For this example you will need the following using directives:

using CodeScales.Http;
using CodeScales.Http.Methods;
using CodeScales.Http.Entity;
using CodeScales.Http.Common;

We start by creating the HttpClient object and the POST method (very much the same as we created the GET method). (lines 1-2)

We then create a List of “NameValuePair” and populate it with the values we want to send. Any other C# type (like int) that you want to pass as a parameter will have to be converted to string since in “HTTP Form Post” all parameters are passed as strings. (lines 4-5)

Once we have the list of parameters, we create a UrlEncodedFormEntity which is the entity that transforms our list of parameters to an “HTTP Form Post” content. We will then assign the UrlEncodedFormEntity to be the PostMethod’s entity. (lines 7-8)

To Conclude, we will execute the PostMethod (line 10). Once executed, as before, we can check the status code, and print the markup of the response.

HttpClient client = new HttpClient();
HttpPost postMethod = new HttpPost(new Uri("http://www.w3schools.com/asp/demo_simpleform.asp"));

List<NameValuePair> nameValuePairList = new List<NameValuePair>();
nameValuePairList.Add(new NameValuePair("fname", "brian"));
            
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Encoding.UTF8);
postMethod.Entity = formEntity;
            
HttpResponse response = client.Execute(postMethod);

Console.WriteLine("Response Code: " + response.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));


Send a GET request via a proxy server

This code example is very similar to the first GET example. The only difference here is the line of code that tells the HttpClient the address of the proxy server.


HttpClient httpClient = new HttpClient();
 httpClient.Proxy = new Uri("http://localhost:8888/"); // default address of fiddler
 HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com"));
 HttpResponse httpResponse = httpClient.Execute(httpGet);

 Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
 Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

You can use the Fiddler tool as a local proxy on your machine to test the proxy functionality. The Fiddler tool also helps a lot with debugging issues related to Http communication. See the “Http Tools” section on the right to download fiddler.


Send a GET request and control redirects

There are two ways to control redirects in this version of HttpClient. The first way to control redirects is simply by specifying the maximum number of redirects, the HttpClient is allowed to perform.

using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Methods;

HttpClient httpClient = new HttpClient();
httpClient.SetMaxRedirects(0);
HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com/home"));
HttpResponse httpResponse = httpClient.Execute(httpGet);

Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

In this example we have set the maximum number of redirects to zero. this means that the HttpClient might receive a 302 or 301 status code from the server, but it will not send another request to the new Location of the resource. The same way we could have limited the number of redirects to two: this would have resulted in the HttpClient receiving a 302/301 status code from the server, with a new Location, and then automatically issuing another GET request to the new Location. The response object that is returned, will reflect the last response received. You can see the new Location received using the following API:


Console.WriteLine("Response Code: " + httpResponse.Location);

The second way to control redirects is by using the HttpBehavior class.

This time we will create an “HttpBehavior” class to control the redirects. We will tell it exactly what are steps we expect the HttpClient to perform. Then when we execute the GetMethod (line 12), we pass the HttpBehavior object to the HttpClient as a parameter, and the HttpClient will make sure every request and response cycle matches exactly the behavior we expect.

using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Methods;

HttpClient httpClient = new HttpClient();
HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com/home"));

HttpBehavior httpBehavior = new HttpBehavior();
httpBehavior.AddStep(301, "http://www.codescales.com");
httpBehavior.AddStep(200);

HttpResponse httpResponse = httpClient.Execute(httpGet, httpBehavior);

Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
Console.WriteLine("Response Code: " + httpResponse.Location);
Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

This example will send a GET request to “http://www.codescales.com/home”, and it will expect to receive a 301 response with “http://www.codescales.com” as the new location. Then it will send another GET request to the new location, and it will expect the response to have a 200 status code.
Any deviation from this behavior will result in an HttpBehaviorException thrown.


Send a GET request using HttpClient

This is the most basic example of using HttpClient to send a GET request. In the example we create an HttpClient instance, then create the HttpGet method (passing it the URL of the resource we would like to obtain), and then we execute the request by passing the GET method to the HttpClient Execute method.

The return parameter is the HttpResponse object, that holds the “response code” and the actual response content (in this case, is an HTML page).

using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Methods;

HttpClient httpClient = new HttpClient();
HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com"));
HttpResponse httpResponse = httpClient.Execute(httpGet);

Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

In the console you will see as the result, the response code, and all the HTML of the page you were requesting. As you already understand you will not see any visual representation as a result of executing a request, but you get access to the markup that returns as part of the response.


Copyright © 2010 CodeScales.com
iDream theme by Templates Next | Powered by WordPress