I am trying to upload an image for whataspp cloud api , i've transformed curl code to c# using RestSharp but i got this error . I was triying to change the file parameter format but it doesn't work. I don't know if i am missing something in the json maybe.
here is the code i use :
public void whatsapp_image_upload()
{
var client = new RestClient("https://graph.facebook.com/" + num_whatsapp_business + "/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + token_authorization);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("messaging_product", "whatsapp");
request.AddParameter("file", "C:\\Users\\cnarea\\Pictures\\empaque.jpg");
request.AddParameter("type", "image/jpeg");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
and this is the error i recieve :
{"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AFWXnEVRuvp82ewjaUEtoLa"}}
Well i was able to solve it, i have to use postman app to obtain c# code ,my code is this :
public void whatsapp_image_upload()
{
try
{
string filePath = #"C:\Users\cnarea\Pictures\procesos.jpeg";
var client = new RestClient("https://graph.facebook.com/"+num_whatsapp_business+"/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer "+token_authorization);
request.AddFile("file", filePath, "image/jpeg");
request.AddParameter("messaging_product", "whatsapp");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Related
I need to display an image as if using normal HTML, but I can't provide a normal url to the image for security reasons. Instead I need to retrieve the image from a WebApi service. I found this:
https://stackoverflow.com/a/24985886/1481314
And, I've looked at the links provided in the answers, but something isn't working. All I'm getting is a missing image placeholder.
This is my code - client-side:
angular.element('#' + imageType + '_' + itemID).html('<img src="/api/filemanagermaindata/getFile?systemName=' + baseData.CustomerData.SystemName + '&fileID=' + id + '" />')
This is my WebApi Controller Method
[HttpGet]
[Route("api/filemanagermaindata/getFile")]
public HttpResponseMessage GetFile(string systemName, int fileID)
{
var customerData = ValidateUser(systemName, 0);
var response = this.fileMover.GetFileDataHttpResponse(customerData.OrganizationID, fileID);
return response;
}
And my class method that gets and returns the image...
var response = new HttpResponseMessage();
try
{
FileManagerItem item = this.dataService.GetFileByID(fileID);
var fullPath = this.rootLocation + Path.Combine( item.PhysicalPath, item.Name);
if (!File.Exists(fullPath))
{
throw new Exception("Unable to locate the requested file");
}
var fileType = Path.GetExtension(item.Name).Replace(".", string.Empty);
if (ApplicationSettings.Instance.ImageFileExtensions.Contains(fileType))
{
fileType = string.Format("image/{0}", fileType);
}
using (FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
{
response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);
response.Content.Headers.ContentLength = fileStream.Length;
};
return response;
}
Dumb mistake. The using {} block was killing the FileStream before the data was loaded.
I'm making a call to an API that consists in a HTTP Post request. The data i want to post is an image, properly converted into a byte array.
The response is not as expected, and i want to know what is the error: is it my code or is it the API? This is the code that i'm using
Image i = new Image();
BitmapImage bi = new BitmapImage(new Uri("/Images/dmoc.jpeg", UriKind.Relative));
testImage.Source = bi;
byte[] rawimage = ImageConverter.ImageToBytes(bi);
try
{
var baseAddress = new Uri("http://private-anon-6cf48a749-yugiohprices.apiary-mock.com/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
//HttpRequestHeader.ContentType
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));
using (var response = await httpClient.PostAsync("api/match_card_image", new ByteArrayContent(rawimage)))
{
string responseData = await response.Content.ReadAsStringAsync();
postTxt.Text = responseData;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.StackTrace);
}
where ImageConverter is my class.
I've got a simple web api which is consumed from a mvc project, I keep on getting the 'Response status code does not indicate success' and was wondering how would I get the response body from the error, I can see the error within a rest viewer but can't navigate through to the error. This is the following code within the MVC app
public ActionResult Index()
{
try
{
var uri = "http://localhost:57089/api/values";
using (var client = new HttpClient())
{
Task<string> response = client.GetStringAsync(uri);
object result = JsonConvert.DeserializeObject(response.Result);
return (ActionResult) result;
}
}
catch (Exception ex)
{
return Content(ex.ToString());
}
return View();
}
Within the API controller I'm sending a bad request, here's the code
public IHttpActionResult Get()
{
return BadRequest("this is a very bad request " + System.DateTime.Now.ToUniversalTime());
}
I've tried to use WebException, HttpRequestException as exceptions to catch the error with no luck.
I can see the response body within the rest viewer
I want to be able to navigate to the Error Message so I can pass that to the client (which later will be changed to a guid).
[EDITED]
I've got a solution without using GetStringAsync, but wanted to use that if possible.
Here's the solution
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
HttpResponseMessage responseMessage = httpClient.GetAsync("").Result;
if (responseMessage.IsSuccessStatusCode) return Content(responseMessage.ToString());
var a = responseMessage.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<HttpError>(a);
object value = "";
return Content(result.TryGetValue("ErrorMessage", out value) ? value.ToString() : responseMessage.ToString());
Is there a better way?
Using WebException you should be able to get to the ResponseStream and the custom error message like this:
catch (WebException e)
{
var message = e.Message;
using (var reader = new StreamReader(e.Response.GetResponseStream()))
{
var content = reader.ReadToEnd();
}
}
Hope that helps.
i am developing an windows phone 8 app , in my app i am calling services and downloading some data into my app .
i am using httpwebrequest for request, but i am not able to set timeout to my httpwebrequest object.
This is how i have created and used my httpwebrequest :-
public async Task<string> ServiceRequest(string serviceurl, string request, string methodname)
{
string response = "";
try
{
var httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
httpwebrequest.Method = "POST";
httpwebrequest.Headers["SOAPAction"] = "http://tempuri.org/" + iTestservice + "/" + methodname + "";
httpwebrequest.ContentType = "text/xml";
byte[] data = Encoding.UTF8.GetBytes(request);
using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream, httpwebrequest.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
response = await httpRequest(httpwebrequest);
}
catch (Exception ex)
{
return null;
}
return response;
}
public async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
My Doubt is :-
1) How can i set timeout property to Httpwebrequest ??
2)What are the different ways in which i can set the timeout property in my windows phone 8 app ??
Please let me know .
Thanks in Advance.
You can't use HttpWebRequest.Timeout on Windows Phone because it doesn't exist for that platform.
If you're open to using a beta library, you could install HttpClient via NuGet and use its Timeout property.
Otherwise, you're probably best off to use TaskEx.Delay, which is part of Microsoft.Bcl.Async. After installing that library, you would replace this line:
response = await httpRequest(httpwebrequest);
with this:
var httpTask = httpRequest(httpwebrequest);
var completeTask = await TaskEx.WhenAny(httpTask, TaskEx.Delay(5000));
if (completeTask == httpTask)
return await httpTask;
else
return null; // timeout
You can use HttpStatusCode.HttpStatusCode is an enum which can be used to get the type of error in HttpWebRequest.
catch(WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if(response.StatusCode==HttpStatusCode.GatewayTimeout)
{
}
}
The GatewayTimeout indicates that an intermediate proxy server timed out while waiting for a response from another proxy or the origin server.For more information you can refer to the msdn
site for this.Hope it helps
I'm attempting to build a GET webservice that would from website 1 initiate a GET request...sending that request to website 2 and website two would respond by sending a list of objects. I using Json.net to serialize and deserialize the List of objects.
I've put together a POST webservice with the assistance of this question.. WebService ASP.NET MVC 3 Send and Receive
But I've been unsuccessful so far at adapting that example for my new requirement.
Here is what I have so far from website 1..
public static List<ScientificFocusArea> ScientificFocusAreas()
{
string apiURL = "http://localhost:50328/Api/GetAPI";
//Make the post
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
//var bytes = Encoding.Default.GetBytes(body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
Stream stream = null;
try
{
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = -1;
request.Method = "GET";
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
List<ScientificFocusArea> listSFA = WebService.GetResponse_ScientificFocusArea(request);
return listSFA;
}
public static List<ScientificFocusArea> GetResponse_ScientificFocusArea(HttpWebRequest request)
{
List<ScientificFocusArea> listSFA = new List<ScientificFocusArea>();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var end = string.Empty;
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
listSFA = JsonConvert.DeserializeObject<List<ScientificFocusArea>>(end);
}
response.Close();
}
}
return listSFA;
}
Then on the website 2...
public class GetAPIController : Controller
{
//
// GET: /Api/GetAPI/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetScientificFocusAreas()
{
//Get list of SFAs
List<ScientificFocusArea> ListSFA = CreateList.ScientificFocusArea();
string json = JsonConvert.SerializeObject(ListSFA, Formatting.Indented);
//Send the the seralized object.
return Json(json);
}
}
Also, on website 2, I've registered this route for the incoming request...
context.MapRoute(
"GetScientificFocusAreas",
"Api/GetAPI/",
new
{
controller = "GetAPI",
action = "GetScientificFocusAreas",
id = UrlParameter.Optional
}
);
I'm currently getting the error.. he remote server returned an error: (404) Not Found.
Any help would me greatly appreciated.
The problem seems like a routing issue. I would start with the RouteDebugger which can be found here. This tool gives insight into which routes your URL is hitting.
The code I use for a HTTP GET is a bit different that what you have above. It's included below.
public T Get<T>(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var end = string.Empty;
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
response.Close();
JsonSerializer serializer = new JsonSerializer();
serializer.Binder = new DefaultSerializationBinder();
JsonReader jsonReader = new JsonTextReader(new StringReader(end));
T deserialize = serializer.Deserialize<T>(jsonReader);
return deserialize;
}
}
catch (Exception ex)
{
throw new ApiException(string.Format("An error occured while trying to contact the API. URL: {0}", url), ex);
}
}
The other issue I see is in the GetScientificFocusAreas() method. On the second line of the code the objects are converted to JSON. Which is fine, but the last line of code the json is passed into the Json() method. Which converts the string into Json yet again. When using the JSON.Net library use the Content() method in the return instead of Json() and set the content type to application/json
The reasoning for using an external Json converter rather than the internal converter is simply the internal json converter has a few known issues. JSON.Net has been around for years and is solid.