HttpWebRequest POST in c# - c#

I have an Api that allows users to be inserted into the database. I am trying requesting the Api in a windows forms application but keep getting System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'I am relatively new to Api requests. Can anyone see what I am doing incorrectly, thanks.
Customer class:
public class Customer
{
public int StoreCustomerID { get; set; }
// Actaul customer from store ID
public string Number { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string MobilePhone { get; set; }
public System.DateTime DOB { get; set; }
public string Phone { get; set; }
//public User Credentials { get; set; }
public string DeviceToken { get; set; }
//public CustomerCard Details { get; set; }
public string Gender { get; set; }
public bool IsError { get; set; }
public string ErrorMessage { get; set; }
//Public Property StoreNumber As Integer
public string Token { get; set; }
public bool Authenticated { get; set; }
public string SecretKey { get; set; }
}
ApiRequest class:
private void button1_Click(object sender, EventArgs e)
{
Customer cust = new Customer();
InsertUpdateCustomer(cust, "http://Example.com");
}
public static Customer InsertUpdateCustomer(Customer MyCustomer, string ServerAddress)
{
//Dim PostData As New CardInfo With {.CardNumber = CardNumber, .Reference = Reference, .SaleDate = DateTime.Now, .SaleTotalAmount = Amount, .StoreNumber = StoreNumber, .TransactionTypeID = Transaction}
//Customer Res = new Customer();
string webAddr = ServerAddress + "/api/Customer/Insert";
WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("X-Giftworx-App", "Posworx");
httpWebRequest.Timeout = 4000;
MyCustomer.Name = "Janice";
MyCustomer.Surname = "Alexander";
MyCustomer.Email = "j#example.com";
MyCustomer.MobilePhone = "0314011828";
MyCustomer.Gender = "Female";
MyCustomer.DOB = DateTime.Now;
MyCustomer.Token = "wMq0cZ4iN7uOnJdrSdYITQcWHQ9VYgiLCosN7Rj9MSdqmZKSTuHCb08jeO/wlp3bCoK/sbEwwvjlZUeQdj8p5w==";
MyCustomer.SecretKey = "jdghe45";
MyCustomer.Authenticated = true;
try
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
//Serialize the Record object to a memory stream using DataContractJsonSerializer.
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customer));
ser.WriteObject(stream1, MyCustomer);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine("JSON form of Insert Loyaltyworx Update Customer object: ");
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
}
catch (Exception ex)
{
return null;
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(JObject.Parse(result));
Customer MyResult = JsonConvert.DeserializeObject<Customer>(result);
Debug.WriteLine(JObject.Parse(result));
return MyResult;
}
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
}

You can convert your data in to a json string as below
Customer cust = new Customer();
var json = new JavaScriptSerializer().Serialize(cust );
JObject json2 = JObject.Parse(json);
and then you can make a call like this.
string webAddr = ServerAddress + "/api/Customer/Insert";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.PostAsJsonAsync(webAddr , json2).Result;

Make sure you are lunching your app as administrator and check that the firewall/antivirus is not blocking.

Related

Getting Http Error Code 411 : Length Required

When I am trying to upload a file using following code I am receiving Length Required error. Please note that if I am uploading a TEXT file then I don't see any issues. But when I upload WORD or PDF I am seeing the error. FYI, I am able to see to Content-Length in my request header in both occasions. Any help would be much appreciated.
internal static class CreateFile
{
private static string _Server = "MyServer.com";
private static string _Database = "ACTIVE";
internal static async Task<string> CreateFileInFolder(string _AuthToken, string _FolderId, string _FileLocation)
{
// Force TLS 1.2 instead of the default value.
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//folder creation URI
string _FileCreateUri = $"https://{_Server}/api/v2/customers/1/libraries/{_Database}/folders/{_FolderId}/documents";
FileInfo _FileDetails = new (_FileLocation);
string _Result = "";
FileRoot _FileRoot = new()
{
doc_profile = new FileProfile()
{
author = "ADMIN",
comment = "New Import",
default_security = "private",
name = _FileDetails.Name,
custom1 = "Test",
custom2 = "Test",
custom17 = "12345",
access = "full_access",
database = _Database,
size = _FileDetails.Length,
#class = "DOC",
type = "ACROBAT",
type_description = "",
wstype = "document"
},
audit = new FileAudit()
{
comments = "Test Import"
},
keep_locked = false,
warnings_for_required_and_disabled_fields = true
};
byte[] _FileBytes = File.ReadAllBytes(_FileDetails.FullName);
string _Boundary = $"----------{DateTime.Now.Ticks:x}";
MultipartFormDataContent _MultipartFormDataContent = new(_Boundary)
{
{
JsonContent.Create(_FileRoot), "profile"
},
{
new StreamContent(new MemoryStream(_FileBytes), _FileBytes.Length), "file"
}
};
_MultipartFormDataContent.Headers.Remove("Content-Type");
_MultipartFormDataContent.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={_Boundary}");
using (HttpClient _HttpClient = new())
{
//include authentication token in request header
_HttpClient.DefaultRequestHeaders.Add("X-Auth-Token", _AuthToken);
using (HttpResponseMessage _HttpResMsg = await _HttpClient.PostAsync(_FileCreateUri, _MultipartFormDataContent))
{
if (_HttpResMsg.StatusCode == HttpStatusCode.Created)
{
_Result = _HttpResMsg.Content.ReadAsStringAsync().Result;
}
}
}
//MessageBox.Show($"Json profile newly created folder: {_HttpResMsg.Content.ReadAsStringAsync().Result}", "New Folder Profile", MessageBoxButton.OK);
return _Result;
}
public class FileAudit
{
public string comments { get; set; }
}
public class FileProfile
{
public string author { get; set; }
public string access { get; set; }
public string comment { get; set; }
public string #class { get; set; }
public string database { get; set; }
public string default_security { get; set; }
public string name { get; set; }
public long size { get; set; }
public string type { get; set; }
public string type_description { get; set; }
public string wstype { get; set; }
public string custom1 { get; set; }
public string custom2 { get; set; }
public string custom17 { get; set; }
}
public class FileRoot
{
public FileProfile doc_profile { get; set; }
public FileAudit audit { get; set; }
public bool keep_locked { get; set; }
public bool warnings_for_required_and_disabled_fields { get; set; }
}
}
Tried to use HttpRequestMessage by setting Content-Length but again able to upload TEXT files but not WORD or PDF files.

Using IMDB-API and when I make a call I am not receiving anything back

I am writing a program using the IMDB web api (https://imdb-api.com/) however when I am making a call with it I am not receiving any data back, I have reached out to them a few weeks ago but still not heard any response. The apiKey is correct and part of another function.
Below is the api I call I am making:
private void SearchForMovie()
{
string hostURL = "https://imdb-api.com/eng/API/SearchMovie/" +apiKey+ "/" + Searchbar.Text;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(hostURL);
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string jsonData = objReader.ReadToEnd();
searchData = JsonConvert.DeserializeObject<SearchData>(jsonData);
MessageBox.Show(searchResult.Id);
}
And this is the .Json file that on there website said I should use:
using System.Collections.Generic;
public class SearchData
{
public string SearchType { get; set; }
public string Expression { get; set; }
public List<SearchResult> Results { get; set; }
public string ErrorMessage { get; set; }
}
public class SearchResult
{
public string Id { get; set; }
public string ResultType { get; set; }
public string Image { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public enum SearchType
{
Title = 1,
Movie = 2,
Series = 4,
Name = 8,
Episode = 16,
Company = 32,
Keyword = 64,
All = 128
}

Fetching data from Json and displaying it in Combobox

I am trying to get a json file using a url and deserialize the json and display a particular field in the combobox but nothing shows up
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new
DataContractJsonSerializer(typeof(RootObject));
RootObject obj = (RootObject)deserializer.ReadObject(ms);
foreach (var name in obj.name)
{
comboBox1.Items.Add(obj.name);
}
}
this is the POCO class
public class RootObject
{
public string name { get; set; }
public List<string> topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public List<string> callingCodes { get; set; }
public string capital { get; set; }
public List<object> altSpellings { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public List<object> latlng { get; set; }
public string demonym { get; set; }
public double? area { get; set; }
public double? gini { get; set; }
public List<string> timezones { get; set; }
public List<object> borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public List<Currency> currencies { get; set; }
public List<Language> languages { get; set; }
public Translations translations { get; set; }
public string flag { get; set; }
public List<object> regionalBlocs { get; set; }
public string cioc { get; set; }
}
I want to display the name in the combobox
here is the link to the json
https://restcountries.eu/rest/v2/all/
You was trying deserialized one result, however result are list.
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new
DataContractJsonSerializer(List<RootObject>); //TODO: FIXED
List<RootObject>obj = (List<RootObject>)deserializer.ReadObject(ms); //TODO: FIXED
foreach (var name in obj.name)
{
comboBox1.Items.Add(obj.name);
}
}
it´s work
Add manage nuget package : Newtonsoft.Json
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
dynamic dyn = JsonConvert.DeserializeObject<List<CountryName>>(json);
foreach (var item in dyn)
{
comboBox1.Items.Add(item.name);
}
public class CountryName
{
public string name { get; set; }
}
Best and fast approach and it's working fine
#A.M.Patel
i couldn't able to post it in the comment section
the code u sent worked perfectly
i too used newtonsoft.json
if iam not annoying you
can u spot out my mistakes in my code
1st code which i tried for single entry
HttpClient http = new HttpClient();
string url = "https://restcountries.eu/rest/v2/alpha/ind";
HttpResponseMessage response = http.GetAsync(new Uri(url)).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
var countries = JsonConvert.DeserializeObject(responseBody);
var details = JObject.Parse(countries.ToString());
comboBox1.Items.Add(countrynames);
it worked well
2nd code which i tried for multiple entries it doesn't showed any values in the combobox the combobox remained empty
HttpClient http = new HttpClient();
IDictionary<String, Int32> countrycounts = new Dictionary<String, Int32>();
string url = "https://restcountries.eu/rest/v2/all/";
HttpResponseMessage response = http.GetAsync(new Uri(url)).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
var countries = JsonConvert.DeserializeObject(responseBody);
var details = JObject.Parse(countries.ToString());
foreach (var obj in details){
string countrynames = details["name"].ToString();
if (countrycounts.ContainsKey(countrynames))
{
int count = countrycounts[countrynames];
count++;
countrycounts[countrynames] = count;
comboBox1.Items.Add(countrynames);
}
else { comboBox1.Items.Add(countrynames); }

Read Json from file and display [duplicate]

This question already has answers here:
Android app Json
(2 answers)
Closed 7 years ago.
I writing android app and have API
Writing API to file like this
Code of writing:
string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.Write(json.ToString());
streamWriter.Close();
}
ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);
}
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
And I need to read some fields from file
I try to do it like this but it didn't work
Code:
private void ParseAndDisplay1(JsonValue json)
{
TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
TextView price = FindViewById<TextView> (Resource.Id.price);
TextView weight = FindViewById<TextView> (Resource.Id.weight);
productname.Click += delegate {
var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
StartActivity (intent404);
};
string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine (path, "myfile.txt");
using (var streamReader = new StreamReader (filename, true)) {
JsonValue firstitem = json [81];
productname.Text = firstitem ["post_title"];
price.Text = firstitem ["price"] + " грн";
weight.Text = firstitem ["weight"] + "г";
}
}
Can you help me with this problem?
Here's a simple way to read the JSON and manipulate it using Json.NET that you can install from Xamarin:
var url = "http://new.murakami.ua/?mkapi=getProducts";
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Since you're just downloading the json you can use a webclient
using (var wc = new WebClient())
{
// Download the json data
var jsonData = await wc.DownloadStringTaskAsync(new Uri(url));
// Save the json data
File.WriteAllText(Path.Combine(path, "myfile.txt"), jsonData);
// Deserialize the Json into a list of object of the type YourObject
List<YourObject> list = JsonConvert.DeserializeObject<List<YourObject>>(jsonData);
// Do whatever you want to do with the data
foreach (var yourObject in list)
{
// this is just an example
Console.WriteLine(yourObject.post_title);
}
}
And this is the definition of the YourObject class:
// this will hold the deserialized objects and make it easy to use
// You can delete properties you don't need
public class YourObject
{
public int ID { get; set; }
public string post_author { get; set; }
public string post_date { get; set; }
public string post_date_gmt { get; set; }
public string post_content { get; set; }
public string post_title { get; set; }
public string post_excerpt { get; set; }
public string post_status { get; set; }
public string comment_status { get; set; }
public string ping_status { get; set; }
public string post_password { get; set; }
public string post_name { get; set; }
public string to_ping { get; set; }
public string pinged { get; set; }
public string post_modified { get; set; }
public string post_modified_gmt { get; set; }
public string post_content_filtered { get; set; }
public int post_parent { get; set; }
public string guid { get; set; }
public int menu_order { get; set; }
public string post_type { get; set; }
public string post_mime_type { get; set; }
public string comment_count { get; set; }
public string filter { get; set; }
public object img_url { get; set; }
public string visibility { get; set; }
public string price { get; set; }
public string weight { get; set; }
public string energy { get; set; }
public string sku { get; set; }
public int category { get; set; }
}

Asp.Net WebApi - Post a file

Can anyone give me some light about this problem? I've been trying to post a file and some parameters to an WebApi, but using multipart/form-data didn't work at all. What can i do? Here's the code from:
-Client-
public string Put(string appkey, string senha)
{
string url = $"{"http://localhost:59701"}/api/Ocr";
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(1, 1, 1);
string xml = "";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("Id", Guid.NewGuid().ToString()),
new KeyValuePair<string, string>("Key", "awesome"),
new KeyValuePair<string, string>("From", "khalid#home.com")
//other values
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
multipartFormDataContent.Add(new ByteArrayContent(Arquivo), '"' + "File" + '"', NomeArquivo);
var result = client.PutAsync(url, multipartFormDataContent).Result;
}
}
return xml;
}
-WebApi-
public class OcrController : ApiController
{
[HttpPut]
public void Extrair(CourierMessage input)
{
//do anything
}
}
public class CourierMessage
{
public string Id { get; set; }
public string Key { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public DateTimeOffset Processed { get; set; }
public DateTime Received { get; set; }
public DateTime Created { get; set; }
public DateTime Sent { get; set; }
public HttpPostedFileBase File { get; set; }
}
Is there a way to bind every property to an object just like we do in MVC?

Categories

Resources