It is my first time to ask a question in here (I'm from Asia).
Platform:UWP 17632
IDE : Visual Studio 2017
Based on the reqiurement of the project, I need to post some information to a website.
I refer the answer about How to make HTTP POST web request Method A.
Here is my code:
public async void PostDataAsync(string pTemperture, string pHumidity, string pFireStatus, string pLightStatus, string pBodyStatus)
{
var values = new Dictionary<string, string>
{
{"count", "1" },
{"temperture_0", pTemperture },
{"Humidity_0", pHumidity },
{"FireStatus_0", pFireStatus },
{"LightStatus_0" ,pLightStatus},
{"BodyDetect_0", pBodyStatus }
};
var content = new FormUrlEncodedContent(values);
try
{
var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);//Here throw an exception
System.Diagnostics.Debug.WriteLine(response);
var responseString = response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.HelpLink);
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}
And then it throws an exception
“An error occurred while sending the request.”
in
var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);
I want to know why and gain the solution which can solve it.
I will be grateful if you can help me.
It is recommend that use HttpClient and the rest of the Windows.Web.Http namespace API to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols within UWP.
For your requirement, you could make a method to package http POST method like the follow
public async void SendPostMethod(string url, Dictionary<string, string> param, Action<string> response)
{
HttpClient client = new HttpClient();
HttpResponseMessage httpResponse = new HttpResponseMessage();
Uri requestUri = new Uri(url);
var content = new HttpFormUrlEncodedContent(param);
try
{
httpResponse = await client.PostAsync(requestUri, content);
response(await httpResponse.Content.ReadAsStringAsync());
}
catch (Exception ex)
{
}
}
Usage
this.SendPostMethod("http://115.159.36.210/api/onehome/upload",Param, (res) =>
{
var response = res;
});
And there are official code sample and document that you could refer.
I am the author of the server.
The reality is I have not finish the code of the server.
Thus , {"status":-1,"msg":"Error! Invalid Request."} is the default result .....
Related
I am trying to download pipeline artifacts from an Azure Devops Pipeline.
The artifacts are zip files. I have been referencing this post,
https://andrewlock.net/downloading-artifacts-from-azure-devops-using-dotnet/
and am nearly there.
Problem is, when I go to extract my zip files to check the content windows explorer says they are empty. I have tried other tools as well, same thing. I know the artifact is valid and the download url is valid, because I can break on entry to the following function and check the url. It matches up with what I get if I use the web UI.
Has to be something I am doing wrong with the download/creation of the zip file. Any help would be appreciated.
static private async Task DownloadArtifactWithHttpClient(string artifactDownloadUrl, string artifactName, string downloadPath)
{
try
{
var localZipFilePath = downloadPath + $"\\{artifactName}.zip";
// Use HttpClient to download the artifact
using (var tempClient = new HttpClient())
{
// Send request to the DownloadUrl specificed in the BuildArtifact
HttpResponseMessage response = await tempClient.GetAsync(artifactDownloadUrl);
if (!response.IsSuccessStatusCode)
{
// Something went wrong, shouldn't happen
throw new Exception($"Error downloading artifact: {response.StatusCode}:{response.ReasonPhrase}");
}
// Save the stream to a file
using (Stream zipFile = File.Create(localZipFilePath))
{
await response.Content.CopyToAsync(zipFile);
}
}
// All done!
Console.WriteLine($"Done downloading too, {localZipFilePath}");
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
if (ex.InnerException != null) Console.WriteLine("Detailed Info: " + ex.InnerException.Message);
Console.WriteLine("Stack:\n" + ex.StackTrace);
}
}
I realized my mistake. I wasn't authenticating the new HttpClient.
Earlier in the example the 'Microsoft.VisualStudio.Services.WebApi.VssConnection' was authenticated with our PAT and was used to get a BuildHttpClient to work with. That client was what I used to get the download URL.
The new HttpClient isn't authenticated in the example. However, I kept digging and looked at the REST API offered by MS and they show how to authenticate an HttpClient with a PAT in this example getting a list of projects
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/projects"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
After doing that in my function above, my downloads succeeded.
The response was succeeding with a 203 vs 200 code previously.. Should have been my first clue. Now I know.
I am trying to write a class that will post a json object to an API. If I post the following through Postman (passing it as raw json), the API responds with a 200:
[{"Id":"1","Name":"First of Two","obdOdometer":{"Time":"2020-01-01","Value":"112233"}},{"Id":"2","Name":"Second of Two","obdOdometer":{"Time":"2020-02-03","Value":"45506"}}]
However, I am getting errors when using my class.
Here is the class I am trying to use:
public async Task TransmitobdOdometer(string json)
{
string bearerToken = _config.GetSection("PilotTmwApiSettings:BearerToken").Value;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
var res = client.PostAsync("https://localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } )));
try
{
res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
The string being passed into TransmitobdOdometer() is formatted like so:
string odometerValues = "[{\"Id\":\"1\",\"Name\":\"First of Two\",\"obdOdometer\":{\"Time\":\"2020-01-01\",\"Value\":\"112233\"}},{\"Id\":\"2\",\"Name\":\"Second of Two\",\"obdOdometer\":{\"Time\":\"2020-02-03\",\"Value\":\"45506\"}}]";
This returns the error message: "Response status code does not indicate success: 415 (Unsupported Media Type)." I tried adjusting the format of the string being passed in, but I get the same error, so I figured I'd ask for insight into what I may be doing wrong before proceeding further.
Changing the line to
var res = client.PostAsync("localhost:44308/TestDev", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject( new { json } ), Encoding.UTF8, "application/json"));
... fixed the error 415. I am still getting an error, but will move that to a new discussion.
I am making a POST request to a route which is returning JSON data.
[HttpPost("api/v1/testGetAll")]
public object Test([FromBody]object filteringOptions)
{
return myService.GetLogs(filteringOptions).ToArray();
}
Route works fine, filtering works fine, and when I test the route in Postman I get the right response. However this is only a back-end, and I would like to invoke this route from my custom API gateway.
The issue I'm facing is getting that exact response back. Instead I am getting success status, headers, version, request message etc.
public object TestGetAll(string ApiRoute, T json)
{
Task<HttpResponseMessage> response;
var url = ApiHome + ApiRoute;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
response = client.PostAsync(url, new StringContent(json.ToString(), Encoding.UTF8, "application/json"));
return response.Result;
}
catch (Exception e)
{
...
}
}
}
How can I get exact content back?
You need to read the content from response.
var contentString = response.Result.Content.ReadAsStringAsync().Result;
If you wish, you can then deserialize the string response into the object you want returning.
public async Task<TResult> TestGetAll<TResult>(string apiRoute, string json)
{
// For simplicity I've left out the using, but assume it in your code.
var response = await client.PostAsJsonAsync(url, json);
var resultString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TResult>(resultString);
return result;
}
You have to return the response as an HttpResponseMessage.
Try changing your return statement to
[HttpPost("api/v1/testGetAll")]
public IHttpActionResult Test([FromBody]object filteringOptions)
{
return Ok(myService.GetLogs(filteringOptions).ToArray());
}
Please note: This will return the response with status code 200. In case you want to handle the response based on different response code. You can create the HttpResponseMessage like this-
Request.CreateResponse<T>(HttpStatusCode.OK, someObject); //success, code- 200
Request.CreateResponse<T>(HttpStatusCode.NotFound, someObject); //error, code- 404
T is your object type.
And so on...
There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.
This such question is here:
How to post data using HttpClient?
Given the corresponding aclarations, this is the code I have so far:
The methods to call the method who connects with the web server:
private void Button_Click(object sender, System.EventArgs e)
{
//. . . DO SOMETHING . . .
PopulateListView();
//. . . DO SOMETHING ELSE . . .
}
private void PopulateListView()
{
//. . . DO SOMETHING . . .
list = await "http://web.server.url".GetRequest<List<User>>();
//. . . DO SOMETHING ELSE . . .
}
The method than connects with the web server:
public async static Task<T> SendGetRequest<T>(this string url)
{
try
{
var uri = new Uri(url);
HttpClient client = new HttpClient();
//Preparing to have something to read
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
});
HttpResponseMessage response = await client.PostAsync(uri, formContent);
#region - - Envio anterior (NO FUNCIONO, SIN USO) - -
//var stringContent = new StringContent("markString");
//var sending = await client.PostAsync(url, stringContent);
//MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
#endregion
//Reading data
//var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
MainActivity.ConsoleData = json.ToString();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
catch(Exception ex)
{
Console.WriteLine("Error: "+ex.ToString());
return default(T);
}
}
You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.
This web server is already working properly (I tested it out with some plug-in, it work like it should)
This method is supposed to send the "markString" and receive the data back so then i can use it in the app.
I'm making a Xamarin Android application.
Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient.
The problem
The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.
Thanks in advance.
Most deadlock scenarios with asynchronous code are due to blocking further up the call stack.
By default await captures a "context" (in this case, a UI context), and resumes executing in that context. So, if you call an async method and the block on the task (e.g., GetAwaiter().GetResult(), Wait(), or Result), then the UI thread is blocked, which prevents the async method from resuming and completing.
void Main()
{
var test = SendGetRequest("http://www.google.com");
test.Dump();
}
public async static Task<string> SendGetRequest(string url)
{
try
{
var uri = new Uri(url);
HttpClient client = new HttpClient();
//Preparing to have something to read
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
});
HttpResponseMessage response = await client.PostAsync(uri, formContent);
#region - - Envio anterior (NO FUNCIONO, SIN USO) - -
//var stringContent = new StringContent("markString");
//var sending = await client.PostAsync(url, stringContent);
//MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
#endregion
//Reading data
//var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
return json;
}
catch (System.Exception ex)
{
Console.WriteLine("Error: " + ex.ToString());
return string.Empty;
}
}
I'm working on a windows store app where I am using a web service which has parameters for downloading videos that are given below.
[request addValue:Token Id forHTTPHeaderField:#"Authorization"];
Through log_in web services I get the access token which I have to pass as value in the Authorization a request to the HTTP Header.
Token token="hgmgmhmhgm6dfgffdbfetgjhgkj4mhh8dghmge"
I have to send both these parameters with the web service given to me but I am unable to send them as I'm getting the error status code 404 unauthorized.
Here is my code:
System.Net.Http.HttpClient httpClient1 = new System.Net.Http.HttpClient();
httpClient1.DefaultRequestHeaders.Date = DateTime.Now;
httpClient1.DefaultRequestHeaders.Add("Authorization",acesstoken);
var httpResponse1 = await httpClient.GetAsync("http://gbdfbbnbb#gfdh.co/appi/fdbfdses/3/videos");
string vale = await httpResponse1.Content.ReadAsStringAsync();
string responses = vale;
I know my code is wrong and I need to correct it. Help me with your valuable suggestions.
Try this code
using (var client = new HttpClient())
{
try
{
String url = "https://www.example-http-request.com/json";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Authorization", acesstoken)
};
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responsesStr = await response.Content.ReadAsStringAsync();
if (!responsesStr.Equals(""))
{
//http request data now capture in responseToken string.
//you can change name as per your requirement.
String responseOutput = responsesStr;
//now convert/parse your json using Newtonsoft JSON library
// Newtonsoft JSON Librar link : { http://james.newtonking.com/json }
//LoggingModel is a class which is the model of deserializing your json output.
LoggingModel array = JsonConvert.DeserializeObject<LoggingModel>(responseOutput);
bool isSuccess = array.IsSuccessful;
if (isSuccess == true)
{
//if success
}else{
//if login failed
}
}else{
//no response in http request failed.
}
}
catch (Exception ex)
{
//catch exceptio here
}
}