httpclient 502 error xamarin app trasnfering photo via json - json

We are getting 502 error when we try to send photo in Json.
App developed with .NET and Xamarin.Form
var jsonObjGuid = JsonConvert.SerializeObject(ObjGuid);
var jsonObjFiles = JsonConvert.SerializeObject(ObjFiles, Formatting.Indented);
var url = $"{ Session.EndpointURL}{MethodNames.UploadDossierFiles.Value}";
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
httpClient.Timeout = TimeSpan.FromMilliseconds(600000);
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
{
//request.Headers.Add(HeaderKeys.UserAgent.Value, Resources.DefaultUserAgent);
request.Headers.Add(HeaderKeys.UserAgent.Value, "MobileApp");
request.Headers.Add(HeaderKeys.Token.Value, token);
HttpContent ObjGuidContent = new StringContent(jsonObjGuid);
HttpContent ObjFilesContent = new StringContent(jsonObjFiles);
MultipartFormDataContent content = new MultipartFormDataContent
{
{ObjGuidContent, "ObjGuid"},
{ObjFilesContent, "ObjFiles"}
};
request.Content = content;
var response = await Policy.HandleResult<HttpResponseMessage>(message => !message.IsSuccessStatusCode)
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) => { })
.ExecuteAsync(() => httpClient.SendAsync(request));
}
}
}
Sometimes it works but often I get this error.
Any help, suggestions? What do I need to check?

Related

How to upload image to server (using POST) which return json in Windows Phone 8.1 RT?

I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.
I followed this method: How to upload file to server with HTTP POST multipart/form-data
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string
The request return like this:
--a81d2efe-5f2e-4f84-83b9-261329bee20b
Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22
����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��
Can you help me please!
P/s: Here is my convert method
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
This might help
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("my-url", form);
return response.Content.ReadAsStringAsync().Result;
}
Use ByteArrayContent instead of StringContent. That Should work.
And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.

How to return HTML from ASP.NET Web API when given url

I want to create a WEB API that will accept a url and return the url's "HTML" page. Please how should I do this? I believe I have the wrong code. HI am so new to this. Thanks*
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("https://myurl.com");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
Do you mean do something like this?
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
System.Net.WebRequest req = System.Net.WebRequest.Create("https://myurl.com");
using (System.Net.WebResponse resp = req.GetResponse())
using (System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream()))
response.Content = sr.ReadToEnd().Trim();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
My extension for AspNetCore:
public static ContentResult GetDashboardAsHtml(this AbpController controller)
{
var request = WebRequest.Create($"{controller.Request.Scheme}://{controller.Request.Host}/hangfire");
using var response = request.GetResponse();
using var streamReader = new System.IO.StreamReader(response.GetResponseStream());
return new ContentResult
{
Content = streamReader.ReadToEnd().Trim(),
ContentType = "text/html"
};
}

get a response from httpclient postasync in wp8 app

i have the following code that uploads a photo to a web service , i need to get the response from the service , and i'm using httpclient class here's my code
var fileUploadUrl = Globals.baseUrl + "/laravelProjects/VisWall/public/test";
var client = new HttpClient();
photoStream.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(photoStream), "image", "koko");
await client.PostAsync(fileUploadUrl, content).ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
i've just found the answer you shoud read string async from the results content
string stringResponse =await postTask.Content.ReadAsStringAsync();

GetRequestToken is not working in TweetSharp on Windows Phone

I can't use GetRequestToken in TwitterService anymore
and also GetAccessToken!
TwitterService service = new TwitterService("ConsumerKey", "ConsumerKeySecret");
service.GetRequestToken(Constants.CallbackUri, (request, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
Request = request;
var uri = service.GetAuthorizationUri(request);
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(uri));
}
});
it gives me:
'TweetSharp.TwitterService' does not contain a definition for 'GetRequestToken' and no extension method 'GetRequestToken' accepting a first argument of type 'TweetSharp.TwitterService' could be found (are you missing a using directive or an assembly reference?)
I solved it by getting Request Token via Hammock(https://github.com/danielcrenna/hammock)
and here is the code
/// <summary>
/// Gets Twitter Request Token
/// </summary>
private void GetTwitterToken()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "Your Consumer Key",
ConsumerSecret = "Your Consumer Secret",
Version = TwitterSettings.OAuthVersion,
CallbackUrl = TwitterSettings.CallbackUri
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
};
var request = new RestRequest
{
Path = "/request_token"
};
client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
}
and
private void TwitterRequestTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
_oAuthToken = GetQueryParameter(response.Content, "oauth_token");
_oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + _oAuthToken;
if (String.IsNullOrEmpty(_oAuthToken) || String.IsNullOrEmpty(_oAuthTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter"));
return;
}
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(new Uri(authorizeUrl)));
}
and You can do the same with access token.
Have you checked to see if the TweetSharp Library supports Windows Phone 8?

How to send/post the JSON request in windowsphone

Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}