Http get request giving forbidden response in windows phone 8 - windows-phone-8

HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.

var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here

Related

Post string to Rest API results in 400 Bad Request

Sending a post request with a json object transformed into HttpContent, but the result is a 400 Bad request.
Sender
HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonObject = new JObject(new JProperty("id", Id), new JProperty("image", face));
var strJson = JsonConvert.SerializeObject(jsonObject);
var response = _client.PostAsync(_settings.Uri,
new StringContent(strJson, Encoding.UTF8, "application/json"));
Receiver
[HttpPost]
public IActionResult Post([FromBody]string value)
Could you please give me an advise on how to overcome 400 error?
You current code sends an object serialized to json while ASP.NET Core action expects a string serialized to json. The easiest solution would be repeated data serialization
var objectJson = JsonConvert.SerializeObject(jsonObject);
var stringJson = JsonConvert.SerializeObject(objectJson);
var response = _client.PostAsync(_settings.Uri, new StringContent(stringJson, Encoding.UTF8, "application/json"));
It appears that you have an extra Parentheses in your call
var response = _client.PostAsync(_settings.Uri, (new StringContent(strJson, Encoding.UTF8, "application/json"));
(new
Try removing that first.
Cheers

Http Get Request in windows phone 8.1

Iam new to windows phone 8.1 app developement.i got stuck in getting response from API using httpclient get request..can anybody tell the best way to perform the get request from server in windows phone 8.1..thanks in advance
hope the below helps
try{
var client = new HttpClient();
var uri = new Uri("your URI");
//Call. Get response by Async
var Response = await client.GetAsync(uri);
//Result & Code
var statusCode = Response.StatusCode;
//If Response is not Http 200
//then EnsureSuccessStatusCode will throw an exception
Response.EnsureSuccessStatusCode();
//Read the content of the response.
//In here expected response is a string.
//Accroding to Response you can change the Reading method.
//like ReadAsStreamAsync etc..
var ResponseText = await Response.Content.ReadAsStringAsync();
}
catch(Exception ex)
{
//...
}

Sending a photo to server using httpclient class windows phone 8

i'm trying to send a photo to a server using httpclient class but every time i try i get a 0 byte file , here's my code for sending the image
if (e.ChosenPhoto != null)
{
var fileUploadUrl = Globals.baseUrl + "/laravelProjects/VisWall/public/test2";
var client = new HttpClient();
photoStream.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(e.ChosenPhoto), "image", fileName);
HttpResponseMessage result = new HttpResponseMessage();
await client.PostAsync(fileUploadUrl, content).ContinueWith((postTask) =>
{
try
{
result = postTask.Result.EnsureSuccessStatusCode();
}
catch (Exception exc)
{
MessageBox.Show("errorrrrrr");
}
});
}
i've also checked the length of e.ChoosenPhoto and it's not 0
try this piece of code by using MultipartFormDataContent:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(token), "token");
var imageForm = new ByteArrayContent(imagen, 0, imagen.Count());
imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
form.Add(imagenForm, "image", "nameholder.jpg");
HttpResponseMessage response = await httpClient.PostAsync("your_url_here", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string result = response.Content.ReadAsStringAsync().Result;
You could refer these too:
Uploading image and data as multi part content - windows phone 8
How to upload file to server with HTTP POST multipart/form-data
There are plenty of samples out there, which I've not mentioned here. It would be great if you could give a search before you post here.

My Windows Phone app Get empty response (404 Not Found) Scond time, work's great first time;And always work fine if without SSL

I am building my first windowsPhone 8.1 application ,the role of my application is to create connection with server to get information from it, so I am writing the code to do this process by sending json-rpc request to server to get some information ,I am successful to get it in first time but when I send the second request I am receiving an empty response with 404 error (page not found).
But when I call the service without https (http only) it works fine regardless how many time I call it !
public async Task<string> GetDataFromServer(string urlToCall, string JSONData,string RR)
{
string UserName = “XXXXXXX”
string Password = "XXX";
using ( var handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(UserName, Password);
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = null;
try
{
response = await client.PostAsync(urlToCall, new StringContent(JSONData.ToString(), Encoding.UTF8, " application/json"));
string res = response.Content.ReadAsStringAsync().Result;
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog(res);
await g.ShowAsync();
return res;
}
catch (Exception ex)
{
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog("Error is : " + ex.Message);
g.ShowAsync();
return "Error";
}
finally
{
response.Dispose();
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
}
}
}
Again, when call the URL of service (start with https) on first time I got response with seeked data, but second time I receive an empty response with 404 error (page not found) !!
Any help please
Please try to use this solution.
public async Task<string> SendJSONData3(string urlToCall, string JSONData)
{
string UserName = "XXXXXXXXX";
string Password = "XXXXXXXXX";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlToCall);
httpWebRequest.Credentials = new NetworkCredential(UserName, Password);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
{
string json = JSONData;
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
A couple of ideas:
Do not use the .Result property. Just use await instead to avoid deadlocks.
Remove the additional space in front of the media type parameter " application/json"
Enable logging on the webserver and see if the second request arrives on the server.
Get a network trace, for example with Wireshark or Fiddler.
Try puting WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); in your initialization code, as proposed in this answer.

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}