I have a webapi that i want to post json to and then return json. Im using xamarin to create my android app but it doesn't seem to support PostAsJsonAsync method for the httpclient. So im now trying PostAsync method that post httpcontent. So what i want to do is convert my json to so that it is of format httpcontent and json so that i can post it to my webapi. This is my code:
var clientRequest = new ResourceByNameRequest
{
Name = "G60",
UserId = "1"
};
var param = JsonConvert.SerializeObject(clientRequest);
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
var client = new HttpClient();
var cancellationToken = new CancellationToken();
var result = client.PostAsync("https://mctwebapi-test.entrematic.com/api/Resource/ResourceByName?", content, cancellationToken).Result;
return reslist;
this just runs till the timeout. I can't figure out why it doesn't work. If you have any other suggestions on how to post json to webapi using Xamarin im more than happy to try that out!
Plz help!
Related
In my Xamarin Forms app I have a very basic GET request that results in a 504 'Method not allowed' on Android.
This is the controller that I am calling:
[AllowAnonymous]
[HttpGet]
[Route("api/system/backendversion")]
public int GetBackendVersion()
{
return 20200924;
}
This is the code that performs the request
var _client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Content = content,
Version = HttpVersion.Version10
};
var response = await _client.SendAsync(httpRequest);
The problem disappears when I change the HttpClient implementation from "Android" to "Managed".
Also the webrequest works fine in the XF.UWP version of my app.
I believe I put it on Android for a reason, but I'm unsure what the reason was (probably speed). I'm curious what goes wrong here.
Apperantly it breaks because the content (header?) is set to json when there is no json.
I fixed it like this:
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Version = HttpVersion.Version10
};
if (!string.IsNullOrWhiteSpace(json))
{
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
var response = await _client.SendAsync(httpRequest);
this error is similar to iOS where you get an error if you put json body in a get request
if (httpMethod == HttpMethod.Get && !string.IsNullOrWhiteSpace(json))
{
Debugger.Break();//a get request with a body is not allowed on iOS and results in a error https://stackoverflow.com/questions/56955595/1103-error-domain-nsurlerrordomain-code-1103-resource-exceeds-maximum-size-i
}
Trying to post to a web view in Android. I need to pass in headers (username, password, contentType) AND body parameters. Currently I see webView.LoadUrl takes in the url and headers however I do not see any options for loading a url with body and headers. Just for reference Im trying to achieve something similar to this, which works perfectly in iOS:
public void OpenWebPage(ReviewWebRequest request)
{
var nsRequest = new NSMutableUrlRequest
{
Url = new NSUrl(request.Url),
HttpMethod = request.Method
};
var nsHeaders = request.Headers;
nsRequest.Headers = NSDictionary.FromObjectsAndKeys(nsHeaders.Values.ToArray(), nsHeaders.Keys.ToArray());
nsRequest.Body = NSData.FromString(request.BodyString, NSStringEncoding.UTF8);
webView.LoadRequest(nsRequest);
}
Iam sending a POST request from my android app using Xamarin. Iam using HttpClient to make the request
Things I have done:
1) Specified Internet permission
2) Tested the request from Postman for google Chrome
3) Debugged the code step by step
Problem:
1) I get the response as null.
2) Found the issue might be while receiving the response.
Here is my code:-
var resultString = String.Empty;
var registerContent = new StringBuilder();
registerContent.Append("DeviceId=");
registerContent.Append(deviceId);
registerContent.Append("&");
registerContent.Append("Name=");
registerContent.Append(deviceName);
registerContent.Append("&");
registerContent.Append("EncodedAccountNameā€¸=");
registerContent.Append(username);
var client = DataClient.Instance;
var request = new HttpRequestMessage(HttpMethod.Post,new Uri(EndPoints.RegisterDeviceEndPoint, UriKind.Absolute))
{
Content = new StringContent("DeviceId=" + deviceId + "&Name=" + deviceName + "&EncodedAccountName=" + username)
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var result = await client.SendAsync(request);
if (result.StatusCode == HttpStatusCode.OK)
{
resultString = HostUrl.GeAuthorizationtResult(result.Content.ReadAsStringAsync().Result);
}
return resultString;
Any help is appreciated
Thanks
It looks like you have a lot of app-specific code in there, so it's difficult to say what's causing the issue. You can simplify your code by using HttpClient's built-in support for form posts.
var httpClient = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("DeviceId", deviceId),
new KeyValuePair<string, string>("Name", deviceName),
new KeyValuePair<string, string>("EncodedAccountName", username)
};
var response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var resultString = await response.Content.ReadAsStringAsync();
Try this and see if it solves the issue. Otherwise, you'll need to expand on what HostUrl.GeAuthorizationtResult() does.
I'm trying to send a post request using the google api client library but not able to succeed.
This is the snippet I'm using
UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap); //paramMap contains email and password keypairs
HttpRequest request = httpRequestFactory.buildPostRequest(new GenericUrl(Constants.PHP_SERVICE_BASE_PATH + mPath) , urlEncodedContent);
String response = request.execute().parseAsString();
I do not get the expected response. I think it is because the post parameters i.e email and password are not being sent in the correct format. I need to send them in JSON.
NOTE : I'm not using the library for a google web service.
I'm using a Map as input of the JSON. The map is input for the JsonHttpContent used by the post request.
Map<String, String> json = new HashMap<String, String>();
json.put("lat", Double.toString(location.getLatitude()));
json.put("lng", Double.toString(location.getLongitude()));
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
final HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(url), content);
UrlEncodedContent is used for posting HTTP form content (Content-Type: application/x-www-form-urlencoded). If the Content-Type is application/json you should probably use
http://code.google.com/p/google-http-java-client/source/browse/google-http-client/src/main/java/com/google/api/client/http/json/JsonHttpContent.java
Here is my code to send send direct message using scribe. But it gives me null response. What am I doing wrong?
OAuthRequest req;
OAuthService s;
s = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(APIKEY)
.apiSecret(APISECRET)
.callback(CALLBACK)
.build();
req = new OAuthRequest(Verb.POST, "https://api.twitter.com/1/direct_messages/new.format?user_id="+user_id+"&text=my app test");
s.signRequest(MyTwitteraccesToken, req);
Response response = req.send();
if (response.getBody() != null) {
String t=response.getBody();
Log.w("twittersent","twittersent"+t);
}
Can anybody help me ?
Try specifying the format as XML or JSON in your request URL. Also, make sure your entire text file is URL encoded.