Here sendasync() function is how to use I don't know.
I use foreach loop then get mobile number and message is same every time but main problem is SendAsync is how to use I don't know .
[WebMethod(true)]
public static string SendMessage(List<int> ids, string message)
{
foreach (var id in ids)
{
HttpClient client = new HttpClient();
using (mapsEntityDataContext db = new mapsEntityDataContext())
{
tbl_inq edit = db.tbl_inqs.SingleOrDefault(x => x.Inq_Id == id);
var mobile = edit.Contact;
client.BaseAddress = new Uri("http://sms.hspsms.com/sendSMS?username=hspdemo&message=" + message + "&sendername=HSPSMS&smstype=TRANS&numbers=" + mobile + "&apikey=66e12418-8b67-4c2a-9a08-4fd459bfa84c");
client.SendAsync();
}
//client.SendAsync();
}
return "sucess";
}
There are several ways to perform GET and POST requests:
Method A: HttpClient
Currently the preferred approach. Asynchronous. Ships with .NET 4.5; portable version for other platforms available via NuGet.
using System.Net.Http;
POST
using (var client = new HttpClient())
{
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
using (var client = new HttpClient())
{
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
}
Method B: 3rd-Party Libraries
RestSharp
Tried and tested library for interacting with REST APIs. Portable. Available via NuGet.
Flurl.Http
Newer library sporting a fluent API and testing helpers. HttpClient under the hood. Portable. 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: Legacy
using System.Net;
using System.Text; // for class Encoding
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=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 (Also now legacy)
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");
}
Related
I have legacy code that uses HttpWebRequest and it works fine. Microsoft suggests that we use HttpClient. How can I modify it to use HttpClient, in c#?
string authText = "{ "AuthParams":{ "AuthToken":"TokenID", "FirmID":"MSFT", "SystemID":"Systems-Internal", "Version":"1.0", "UUID":"SystemsInternalAPIUser" }}";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://msft.com/api/busnWebService/xbox-games");
JObject data = JObject.Parse(authText);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
string responseText = streamReader?.ReadToEnd();
(JsonConvert.DeserializeObject<CompRoot>(responseText).Data)
.Select(t => new CompanyClass
{
Ticker = t.Ticker,
}).ToList()
Since I can not try the solution with your payload and endpoint, something like the following should solve the problem without testing it.
string authText = "{\"AuthParams\":{\"AuthToken\":\"TokenID\",\"FirmID\":\"MSFT\",\"SystemID\":\"Systems - Internal\",\"Version\":\"1.0\",\"UUID\":\"SystemsInternalAPIUser\"}}";
var content = new StringContent(authText, Encoding.UTF8, "application/json");
using HttpClient client = new HttpClient();
var httpResponse = await client.PostAsync("http://msft.com/api/busnWebService/xbox-games", content);
string responseText = await httpResponse.Content.ReadAsStringAsync();
With HttpClinet you need to use async Task with await. I assume your mapping from the response should be the same. But you need to validate that.
This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
i, tried putting body in request but didn't actually worked,
in body i want to put which is in json format {"ClaimNo":"123123"}
i have used this as code:
string ClaimStatus_url = "https:xyz";
WebRequest request = WebRequest.Create(ClaimStatus_url);
request.ContentType = "application/json";
request.Method = "POST";
//request.Headers = "";// i used this for puting body in it but did not work
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
using System.Text;
using System.Text.Json;
namespace TestPostData;
public class Data
{
public int ClaimNo { get; set; }
}
public static class Program
{
public static void Main()
{
var postData = new Data
{
ClaimNo = 123123,
};
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
var response = client.PostAsync("https:xyz", content).Result;
}
}
That is an example of using HttpClient class that is now recommended to use instead WebRequest.
Try this, i hope it will work.
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();
I would start off by using RestSharp.
dotnet add package RestSharp
Then I would create a DTOS object with the contents that you want to send in the json:
public class DtosObject
{
public string ClaimNo {get; set;}
}
Then pass that in as the object (I would call the class something relevant to the data it contains). If you only are using ClaimNo you could also use a KeyValuePair like this:
var body = new KeyValuePair<string, string>("ClaimNo", "123123");
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
string ClaimStatus_url = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
//string json = "{\"ClaimNo\":\"CV010831\"}";
//await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result1 = "" ;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
}
_claimstaus = GenrateJSON_Claim(result1);
This upper code worked
I have a bot running on http://localhost:3978/api/messages.
Instead of debugging it using an emulator, can I go about using a http post request to the messaging endpoint of the bot?
If so, how do I go about doing it?
I am using c# microsoft bot framework, and I am new to this application.
I do not want to use any channels or DirectLine api, just using Httpclient.
You can do this with C# using code similar to below. Note that you would have to construct an Activity to send by setting the appropriate properties for your needs, which is not included in this code.
//make a call to get an auth token
string token;
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["grant_type"] = "client_credentials";
values["client_id"] = "YOUR APP ID";
values["client_secret"] = "NcOXRwb51joibEfzUuNE04u";
values["scope"] = "YOUR APP ID/.default";
var response =
client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);
var responseString = Encoding.Default.GetString(response);
var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
token = result.access_token;
}
//you will need to adjust this value for your project.
//this example for a proxy project so the service url here is
//just an arbitrary endpoint I was using to send activities to
activity.ServiceUrl = "http://localhost:4643/api/return";
var jsonActivityAltered = JsonConvert.SerializeObject(activity);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", $"Bearer {token}");
try
{
var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Have you tried using something like postman? (it's free and easy to use)
https://www.getpostman.com/
You can also write scripts in postman
otherwise you can just go to the endpoint of your API in the browser
http://localhost:3978/api/
I see you mentioned you wanted to make a console application.
You could do that. I'd suggest using postman though.
Here is an example of sending a file as well as some querystring data and Authentication using a Bearer token.
Sorry it may not be exact. Had to do a bit of copy pasting/deleting from some code examples if have
using (HttpClient client = new HttpClient())
{
JObject jsonModel = new JObject();
client.BaseAddress = new Uri("http://localhost:3978/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("firstname", lastname),
new KeyValuePair<string, string>("lastname", lastname),
new KeyValuePair<string, string>("payloadFile", FileName)
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
ByteArrayContent fileContent = new ByteArrayContent(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
string FullxmlString = File.ReadAllText(Path.Combine(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("payloadFile") { FileName = "payloadFile" };
multipartFormDataContent.Add(fileContent);
HttpResponseMessage response = client.PostAsync("api/message", multipartFormDataContent).Result;
string returnString = response.Content.ToString();
using (HttpContent content = response.Content)
{
string res = "";
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
}
}
I want to add a record to the json service in my application. How can I do this via Service Url. Here is my code.
CustomerModel customer = new CustomerModel();
customer.Name = entryCompanyName.Text;
customer.Title = entryCompanyTitle.Text;
customer.PhoneNumber = entryTelephone.Text;
customer.FaxNumber = entryFax.Text;
customer.Email = entryEmail.Text;
customer.CityId = 6444;
string json = JsonConvert.SerializeObject(customer);
string sContentType = "application/json";
string path = "service url";
HttpClient Client = new HttpClient();
var task = Client.PostAsync(path, new StringContent(json.ToString(), Encoding.UTF8, sContentType));
I'm trying M. Wiśnicki's solution, but I took this error
I did not get an error when I added System.net :( Where do i make mistakes?
This worked for me
public static async Task<string> PostEntityToApi<T>(string yourMethodUrl, T yourModel)
{
try
{
if (_httpClient == null)
{
_httpClient = new HttpClient { BaseAddress = new Uri(yourWebSiteUrl) };
}
var stringContentInput = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(new Uri(yourWebSiteUrl. + apiUrl), stringContentInput);
if (!response.IsSuccessStatusCode)
{
throw new Exception(response.StatusCode.ToString());
}
var stringAsync = await response.Content.ReadAsStringAsync();
LoggingManager.Error("Received error response: " + stringAsync);
return stringAsync;
}
catch (Exception exception)
{
return null;
}
}
You can use WebRequest, this sample working for me, i use it in my app.
This is System.Net.WebRequest class, here you find doc.
public async Task<string> PostSample(object data, string uri)
{
// Create an HTTP web request using the URL:
var request = (HttpWebRequest) WebRequest.Create(new Uri(uri));
request.ContentType = "application/json";
request.Method = "POST";
var itemToSend = JsonConvert.SerializeObject(data);
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(itemToSend);
streamWriter.Flush();
streamWriter.Dispose();
}
// Send the request to the server and wait for the response:
using (var response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
var message = JsonConvert.DeserializeObject<string>(reader.ReadToEnd());
return message;
}
}
}
I have tested/googled for hours on how to POST parameter in C# to an Azure Service without getting the Error 405.
The following code in C++ using Chilkat lib works fine
CkHttp http;
CkHttpRequest req;
http.put_SessionLogFilename("c:/temp/httpLog.txt");
req.put_HttpVerb("POST");
req.put_Path("/api/test?value=1234");
CkHttpResponse *resp = http.SynchronousRequest("http://testservice.cloudapp.net",80,false,req);
if (resp == 0 )
afxDump << http.lastErrorText() << "\r\n";
afxDump << resp->bodyStr() << "\r\n";
delete resp;
But if it uses this c# code i get the Error 405.
string uri = "http://testservice.cloudapp.net/api/test";
string parameter = "value=1234";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(uri, parameter);
}
Any hints what i do wrong?
You'll be better off using HttpClient instead of WebClient . By looking at what the C++ code does it should be something like this in C# using HttpClient
public void Test() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = client.PostAsync("api/test?value=1234", new StringContent(string.Empty)).Result;
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = response.Content.ReadAsStringAsync().Result;
var responseContentAsBYtes = response.Content.ReadAsByteArrayAsync().Result;
}
}
Here is the async version of the code above
public async Task TestAsync() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = await client.PostAsync("api/test?value=1234", new StringContent(string.Empty));
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = await response.Content.ReadAsStringAsync();
var responseContentAsBYtes = await response.Content.ReadAsByteArrayAsync();
}
}