Sending a Post Request with Net/Http

Sending http post request in Ruby by Net::HTTP

The second argument of Net::HTTP#post needs to be a String containing the data to post (often form data), the headers would be in the optional third argument.

POST request to HTTPS using Net::HTTP

Your request hash is being replaced by your request object which you're assigning Net::HTTP. Also be sure to set request params in the body of your HTTP request:

require "active_support/all"
require "net/http"

token = "my_token"
url = "https://graph.facebook.com/v2.6/me/messages?"
sender = 100688998246663
text = "Hello"
request_params = {
recipient: {id: sender},
message: {text: text},
access_token: token
}
request_header = { 'Content-Type': 'application/json' }

uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(uri.path, request_header)
request.body = request_params.to_json

http.request(request)

response = http.request(request)

You may find the following reference helpful: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

Sending a Post request with net/http

I don't know what your problem is but what about something like this

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = data.to_json

response = http.request(request)

Send HTTP POST request in .NET

There are several ways to perform HTTP GET and POST requests:



Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.



  • POST

      var values = new Dictionary<string, string>
    {
    { "thing1", "hello" },
    { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
  • GET

      var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");


Method B: Third-Party Libraries

RestSharp

  • POST

       var client = new RestClient("http://example.com");
    // client.Authenticator = new HttpBasicAuthenticator(username, password);
    var request = new RestRequest("resource/{id}");
    request.AddParameter("thing1", "Hello");
    request.AddParameter("thing2", "world");
    request.AddHeader("header", "value");
    request.AddFile("file", path);
    var response = client.Post(request);
    var content = response.Content; // Raw content as string
    var response2 = client.Post<Person>(request);
    var name = response2.Data.Name;

Flurl.Http

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

    using Flurl.Http;


  • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();
  • GET

      var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();


Method C: HttpWebRequest (not recommended for new work)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader


  • POST

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var postData = "thing1=" + Uri.EscapeDataString("hello");
    postData += "&thing2=" + Uri.EscapeDataString("world");
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
    stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  • GET

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Method D: WebClient (Not recommended for new work)

This is a wrapper around HttpWebRequest. Compare with HttpClient.

Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.

In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, WebClient can still be used.

using System.Net;
using System.Collections.Specialized;


  • POST

      using (var client = new WebClient())
    {
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
    }
  • GET

      using (var client = new WebClient())
    {
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
    }

How to send HTTP post request to another API in c#?

You can try this:

//Yours entity.
MyEntity myEntity;
HttpResponseMessage response;
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://yourApiAdress.com");
//Yours string value.
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MyStringContent", "someString")
});
//Sending http post request.
response = await httpClient.PostAsync($"rest/of/apiadress/", content);
}

//Here you save your response to Entity:

var contentStream = await response.Content.ReadAsStreamAsync();
//Options to mach yours naming styles.
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance
};
//Here you go. Yours response as an entity:
myEntity = await JsonSerializer.DeserializeAsync<MyEntity>(contentStream, options);

Snake case naming policy:

using Newtonsoft.Json.Serialization; //For SnakeCaseNamingPolicy.

public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();

public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

public override string ConvertName(string name)
{
return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
}
}

If yours another API JSON response looks like:

{
"some_object" : "someValue",
}

Then your entity should look like:

public class MyEntity
{
public object SomeObject { get; set;}
}

VB.net HTTP POST request

For those interested in the result. Here is a topic with the solution.

VB.net Open a web page with the form field filled in

Ruby: Can net/http make a GET and POST request simultaneously?

When creating the request you just need to make sure to keep the GET params in the path:

req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}", {
'Referer' => "http://www.example.com/referer",
'User-Agent'=> "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
'Cookie' => $cookie
})

Notice that instead of just uri.path, I append the ? and uri.query to it. This should pass the GET parameters as well as the POST ones.



Related Topics



Leave a reply



Submit