PUT request working in vb.net but not in C#.net - c#

I am developing a REST client in C# that performs the following operation:
It sends a POST request to the server with a query string parameter PolicyId=myhotp and this json data {"uid":"name"}.
The server responds with json data with state id like this {"state":"323434j2hj"}
I extract the value of "state" from the received json data and send
it in another PUT request to the same server with OTP in order to verify. stateid is sent as query string parameter StateId=ihhfueh8f88 and otp is sent as json data {"otp":"123456"}. The server verifies OTP against state id.
But the server responds that the stateid is invalid. Irony is that this same procedure works when I use old way i.e. Microsoft.XMLHTTP to make requests but it doesn't work with HTTP Client. I am not able to transfer state id in query string.
Here is my code using HTTP Client:
User user = new User();
user.uid = "username";
String json = JsonConvert.SerializeObject(user);
MessageBox.Show(json);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = client.PostAsync("api?myhotp", new StringContent(json, Encoding.UTF8, "application/json")).Result;
var contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
var obj = JObject.Parse(contents);
string id = (string)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
String jsonotp = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(jsonotp);
client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
response = client.PutAsync("api?StateId="+id, new StringContent(json, Encoding.UTF8, "application/json")).Result;
contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
Here is the code with Microsoft.XMLHTTP:
Type xmlType = Type.GetTypeFromProgID("Microsoft.XMLHTTP");
dynamic objXML = Activator.CreateInstance(xmlType);
objXML.Open("POST", "http://fqdn/api?PolicyId=myhotp", false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
//objXML.setOption(2, 13056);
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());
var obj = JObject.Parse(objXML.responseText.ToString());
String id = (String)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
json = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(json);
objXML.Open("PUT", "http://fqdn/api?StateId="+id, false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());

Related

HttpWebRequest API call returns bad request but works from postman

I have a customer API endpoint (POST) that works fine from postman.
The Postman settings using which I am able to receive response is like this:
URL:
https://somedomain.com/rest/portal/authenticate
Headers:
"Content-Type":"application/x-www-form-urlencoded"
"Referrer": "10.xx.xx.xx" // Real IP address here
Body: (x-www-form-urlencoded)
"username": "TestAdmin"
"password": "testpassword"
This setting works fine and I am able to get response in postman.
Now from the same laptop, I tried to make a POST call from .Net core 3.1 method. I have tried with this code:
string userName = _config.GetSection("username").Value;
string Password = _config.GetSection("password").Value;
string BaseURL = _config.GetSection("baseURL").Value; // https://somedomain.com/rest
var dict = new Dictionary<string, string>();
dict.Add("username", userName);
dict.Add("password", Password);
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, BaseURL + $"/portal/authenticate")
{ Content = new FormUrlEncodedContent(dict) };
req.Headers.Add("Referer", "10.xx.xx.xx"); // real IP address entered here
var response = client.SendAsync(req).Result;
string responseContent = response.Content.ReadAsStringAsync().Result;
With this approach I am getting Bad request error with "Inavlid user" message.
What am I doing wrong here? Is the request I have built is not same as Postman ?
Once you populate the data in dictionary, build a payload out of it which conforms to
application/x-www-form-urlencoded content type.
var dict = new Dictionary<string, string>();
dict.Add("username", userName);
dict.Add("password", Password);
string payload = BuildPayload(dic);
Function BuildPayload is defined to form the entire uri from dictionary objects :
private string BuildPayload(Dictionary<string, string> dic)
{
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
return builder.ToString();
}
Then you can get create StringContent instance which will provide you http content based on created payload string. If you need encoding pass it as second param otherwise leave it as null.
StringContent request = new StringContent(payload, null, "application/x-www-form-urlencoded");
Then append your custom header with httpclient instance and call the api with the defined request.
httpClient.DefaultRequestHeaders.Add("Referrer","10.xx.xx.xx");
HttpResponseMessage response = await httpClient.PostAsync(<Your api url>, request);
if (response.IsSuccessStatusCode)
{
string resultStr = await response.Content.ReadAsStringAsync();
}

How to pass Json Content in request Body Using http client with DeleteAsync Method (C#)?

Need to pass Json Content in Request body using http client DeleAsync Method in C#.Not able to pass the Request body in DeleteAsync Method.
HttpClient client=new HttpClient();
var Ids = new[] { 100,202,304,866 };
string endpoint=" URL goes here";
string jsonString = JsonConvert.SerializeObject(Ids);
var RequestBody = new StringContent(jsonString, Encoding.UTF8);
var response = client.DeleteAsync(endpoint,RequestBody).Result;
You can do like this. As far as I know you can't have body in DeleteAsync
object jsonObj;
using (HttpClient client = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Delete,
RequestUri = new Uri("yourUrl"),
Content = new StringContent(JsonConvert.SerializeObject(jsonObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);

How to send json request body data in POST request using C#

I am New in C#.
I want to send JSON request body in POST request using C#.
I want To get results from Rest URL but it's showing me status code 500.
How can I format the request body so that I able to get results from the rest URL?
My Request body in JSON -->
{"filter":{"labtestName":[{"labtestName":"Ada"}]}}
code that I tried
string data1 = "{\filter\":{\"labtestName\":[{\"labtestName\":\"Ada\"}]}}";
var RestURL = "https://nort.co.net/v1api/LabTest/Hurlabtest";
HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(data1);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(jsonData, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("apptoken", "72f303a7-f1f0-45a0-ad2b-e6db29328b1a");
client.DefaultRequestHeaders.Add("usertoken", "cZJqFMitFdVz5MOvRLT7baVTJa+yZffc5eVoU91OqkMYl6//cQmgIVkHOyRZ7rWTXi66WV4tMEuj+0oHIyPS6hBvPUY5/RJ7oWnTr4LuzlKU1H7Cp68za57O9AatAJJHiVPowlXwoPUohqe8Ad2u0A==");
HttpResponseMessage response = await client.PostAsync(RestURL, content1);
var result = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<LabtestResponseData>(result);
You are sending the wrong data to the method,
I have corrected it, you can refer to the below code.
myData string is already a JSON string so there is no need to serialize it again.
string myData = "{\"filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
//string data1 = "{\filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
var RestURL = "https://tcdevapi.iworktech.net/v1api/LabTest/HSCLabTests";
HttpClient client = new HttpClient();
//string jsonData = JsonConvert.SerializeObject(myData);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(myData, Encoding.UTF8, "application/json");

How to send post request of Messaging API

What I want to do
I want to send "post request" following the link below. More specifically, when you open the link, you can see "Example request" which goes like this.
'{
"messages":[
{
"type":"text",
"text":"Hello, world1"
},
{
"type":"text",
"text":"Hello, world2"
}
]
}'
In sample it sends two messages but, I just want to send one.
I don't know how to write in C#
Send broadcast message
This is the code where I'm struggling.
// To creat HttpClient
var client = new HttpClient();
// Accesstoken
var accessToken = "my token";
// URL
var url = "https://api.line.me/v2/bot/message/broadcast";
var request = new HttpRequestMessage(HttpMethod.Post, url);
// Request Header
request.Headers.Add("Authorization", "Bearer " + accessToken);
var parameters = new Dictionary<string, string>()
{
{ "type", "text" },
{ "text", "Hello World" }
};
var parameters2 = new Dictionary<string, Dictionary<string, string>>()
{
{ "messages", parameters}
};
var str = #"{""messages"":"" {""type"": ""text"",""text"" : ""Hello World""}""}";
var content = new JObject(str);
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
await client.SendAsync(request);
Of course it doesn't work
question⓵
How can I write the example In C#???
question⓶
If you can, could you provide entire procedure of Send broadcast message from scratch?
PS
For those who are worried, I'm still gathering answers in my first question and also trying to make it work.
I solved the problem.
The procedure is below.
To make a class following this link http://json2csharp.com/
To serialize that
3.
To useu ToString() to a serialized json
And the entire code is like this
// To creat HttpClient
var client = new HttpClient();
// Accesstoken
var accessToken = "my token";
// URL
var url = "https://api.line.me/v2/bot/message/broadcast";
// Post
var request = new HttpRequestMessage(HttpMethod.Post, url);
// Request Header
request.Headers.Add("Authorization", "Bearer " + accessToken);
// To create messages
var message1 = new Message("text", "Hello World1");
var message2 = new Message("text", "Hello World2");
var root = new RootObject();
root.addMessage(message1);
root.addMessage(message2);
// To serialize
var json = JsonConvert.SerializeObject(root);
request.Content = new StringContent(
json.ToString(),
Encoding.UTF8,
"application/json"
);
await client.SendAsync(request);

Can't authenticate correctly with headers (HttpClient)

I've checking many forums but I can't make it work. I'm trying to authenticate with headers to an url that will return a JSON string if authentication were successful. In Postman I simply used Get method with username and password in header to get the JSON data. What changes do I need to make my following C# code achieve same thing? I think I even failed to add username and password into headers.
public async Task<string> LogMeIn(string username, string password)
{
var client = new HttpClient {
BaseAddress = new Uri("http://x.com")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("grant_type","password"),
new KeyValuePair<string,string>("Username ", username),
new KeyValuePair<string,string>("Password", password)
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("/login", content); //should it be GetAsync?
var jsonResp = await response.Content.ReadAsStringAsync();
var jsonResult = JsonConvert.DeserializeObject<JsonResult>(jsonResp); //JsonResult = class for json
return jsonResult.token;
}
}

Categories