sending email via Post httpclient - Xamarin forms - xamarin

I'm trying to send an email via Post more with no results, and it does not generate any error goes through in all processes, is there something wrong with my code?
HttpClient httpClient = new HttpClient();
var content2 = new MultipartFormDataContent();
content2.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Send")), "templateId");
content2.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("Fulano de tal")), "fromName");
content2.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("blablablabal")), "message");
content2.Add(new ByteArrayContent(Encoding.UTF8.GetBytes("fulano#tal.com.br")), "fromMail");
using (var response = httpClient.PostAsync("http://teste.com.br/Mail/Submit", content2).Result)
{
}

Related

Attaching zip file is not working in WEB API, but works via POSTMAN

I have an .net core WEB API method that needs to call another external API (java) which expects .zip file. When try to access the external API via Postman by attaching the file, it is working fine (getting expected response). However when i pass the same parameters via my WEB API code, it is throwing 403-Forbidden error.
Please let me know if i am missing anything....
Thanks in advance!!!
request-header
request-body-file-attached
response-403-error
API code: for connecting to api:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("pane", "forward");
parameters.Add("forward_path", "/store/execute");
parameters.Add("csrf", "1996fe6b2d0c97a8a0db725a10432d83");
parameters.Add("data_format", "binary");
newContent = new FormUrlEncodedContent(parameters);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent con;// = new StringContent("file_name");
//form.Add(con, "file_name");
form.Add(newContent);
var str = new FileStream("D:\\dummy\\xmlstore.zip", FileMode.Open);
con = new StreamContent(str);
con.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file_name",
FileName = "xmlstore.zip"
};
con.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
form.Add(con);
client.DefaultRequestHeaders.Add("Cookie", "JSESSIONID=05DEB277E294CBF73288F2E24682C7EE;");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("user-agent", "1"));
var resp = client.PostAsync("java-api", con).Result;

Can a REST API be used within a Web API service?

I need to create a Web API "wrapper" that is consumed by a client, but in this Web API Service, I actually need to create a POST request to a different REST API service that is running on the same IIS server that does some work and returns StringContent that I pass back to the client via a JSON HttpResponse. Is this possible? Instead of the client making direct calls to the actual REST API and returning data they don't need/want, they would call my Web API service and I would only return them the required data. I know this was done in the old SOAP WSDL model.
If I need the client to pass in a couple parameters that are required for my POST request, would I be having the client use a GET or POST request?
This is an sample code i used call API inside another API using POST method.
using (var client = new HttpClient())
{
string query;
using (var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username", username},
{"password", password}
}))
{
query = content.ReadAsStringAsync().Result;
}
var model = new{
username = txtUsername.Text,
password = txtPassword.Text
};
var json = JsonConvert.SerializeObject(model);
var user = new StringContent(json, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(#"http://localhost/dataagent/api/user/authenticate", user))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
// handle result here
}
}
}

Can't able to send SMS using Twilio Trail Account using C#

I'm just trying to use Twilio to send transaction SMS. I have tried exactly the same code which is provided in the Twilio Documentation
static void Main(string[] args)
{
try
{
// Find your Account Sid and Token at twilio.com/console
const string accountSid = "AC5270abb139629daeb8f3c205ec632155";
const string authToken = "XXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
from: new Twilio.Types.PhoneNumber("+15017122661"),
body: "Body",
to: new Twilio.Types.PhoneNumber("MyNumber")
);
Console.WriteLine(message.Sid);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
in this authToken copy from Twilio console and the TO number is my number which is used to register on Twilio. I also have verified the number in Verified Caller IDs segment in Twilio Console.
From Number initially, I was using the number which is generated by in Twilio Console the Number Belongs to the US but it won't work. After Reading this
Article I used the Exact code provided by Twilio just make the Changes as authToken and TO Number. But still, it won't work.
I have No idea why it Does not Work. is that you Can't Send the message from one country to another country?
As I want to Verify Mobile number by sending code from SMS. so achieve this I'm using
Twilio Verify API here where the Code is generated by Twilio and verified by himself.
this Solve my problem.
TO Send SMS :-
var client = new HttpClient();
var requestContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("via", "sms"),
new KeyValuePair<string,string>("phone_number", "Moblienumber"),
new KeyValuePair<string,string>("country_code", "CountryCode"),
});
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/start?via=$VIA&country_code=$USER_COUNTRY&phone_number=$USER_PHONE
HttpResponseMessage response = await client.PostAsync(
"https://api.authy.com/protected/json/phones/verification/start?api_key=" + "Your Key",
requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
return Ok();
To Verify :-
// Create client
var client = new HttpClient();
// Add authentication header
client.DefaultRequestHeaders.Add("X-Authy-API-Key", "Your Key");
// https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
HttpResponseMessage response = await client.GetAsync(
"https://api.authy.com/protected/json/phones/verification/check?phone_number=phone_number&country_code=country_code&verification_code=CodeReceivedbySMS ");
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}
return Ok();

Drupal 7 Service module node resources attach_file end point

I am implementing a Xamarin Form mobile app to allow post photo to Drupal using service module node resources. http://xxxx.com/{endpoint}/node/4/attach_file
i able to post from POSTMAN with
I tried to implement with c# HttpClient but keep getting response like "401 :Missing required argument field_name"
Please help on my code:
var httpClient = new HttpClient(new NativeMessageHandler());
httpClient.Timeout.Add(new TimeSpan(0, 0, 30));
httpClient.BaseAddress = new Uri(BaseAddress);
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(g_media.GetStream());
streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("form-data");
streamContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("field_name", "field_receipt_image"));
content.Add(streamContent,"files[file]");
var response = await httpClient.PostAsync("node/4/attach_file", content);
response.EnsureSuccessStatusCode();
I had the same issue and used RestSharp to resolve it. Here is the code I used to upload a file to Drupal:
var restClient = new RestClient("http:XXXXXX/attach_file");
var request = new RestRequest(Method.POST);
request.AddFile("files[file]", fileName);
request.AddParameter("field_name", field);
IRestResponse response = restClient.Execute(request);

restsharp AddParameter for POST not working on Mac (mono)

Using RestSharp 104.4.0 on Xamarin 4.2.2.
I cannot figure out why RestSharp does not add the parameter to a POST request. I am hitting a REST API that takes both GET and POST.
Not working POST:
var request_post = new RestRequest ("folder/endpoint.php", Method.POST);
request_post.AddParameter("ref", "some/value");
response = client.Execute(request_post);
Console.WriteLine (response.Content);
Error is saying that ref parameter is required.
Working GET:
var request_get = new RestRequest ("folder/endpoint.php", Method.GET);
request_get.AddParameter("ref", "some/value");
response = client.Execute(request_get);
Console.WriteLine (response.Content);
Update:
It may be adding the parameter but I need to add the parameters as a form.
Thanks, Matt.
// POST request.
//
// This method does not work!
// var request_post = new RestRequest ("folder/endpoint.php", Method.POST);
// request_post.AddParameter("ref", "some/value");
//
// This method does work.
var endpoint = String.Format("folder/endpoint.php?{0}={1}",
"ref", "some/value");
var request_post = new RestRequest (endpoint, Method.POST);
response = client.Execute(request_post);
// Print out headers.
foreach (var header in response.Headers){
Console.WriteLine(header);
}
// Print response.
Console.WriteLine(response.Content)

Resources