Request & Response Windows Phone - windows-phone-7

I need to send request to server appending xml data as below to the url of the server
<User>
<MobileNumber>xxxxxxxxxx</MobileNumber>
<UserAgent>yyyyy</UserAgent>
</User>
I will get back response as follows
<User>
<MobileNumber>xxxxxxxxxx</MobileNumber>
<ModelId>zzzzzz</ModelId>
<AuthKey>aaaaaaaaa</AuthKey>
<UserAgent>yyyyy</UserAgent>
</User>
I want to parse the recieved xml data
What is the proper way to do this in Windows Phone(7)? first request the url with xml and then receive xml
I am new to windows phone development
what classes should be used??
I am very confused in -
WebClient
WebRequest
WebResponse
HttpWebRequest
HttpWebResponse
Edit: I tried the following code to send request, how do I receive the response??
private void Upload()
{
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var uri = new Uri("xxxxxxxxxx", UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "MobileNumber", HttpUtility.UrlEncode("yyyyyyyyy"));
postData.AppendFormat("&{0}={1}", "UserAgent", HttpUtility.UrlEncode("WP7"));
webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
webClient.UploadProgressChanged += webClient_UploadProgressChanged;
webClient.UploadStringAsync(uri, "POST", postData.ToString());
}

Try the following steps
Step 1: add the namespace using System.Net;
Step 2:
public void Upload()
{
WebRequest webRequest;
webRequest = WebRequest.Create(Url + Mobile_No + Request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback), webRequest);
}
Step 3:
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "Test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
Step 4 :
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
}
else
{
//Your response will be available in "Response"
}
}
catch (WebException)
{
//error
}
}
Check this now

Related

Calling a different host from Spring Controller

My localhost is : http://localhost:8585/api/getproducts where i use #Requestmapping(/api/getproducts) in my ProductController to get to my product page.
On click of a button, i need to call an api on a different host :
http://10.120.130.22:9292/ and i tried to use the below code in a new Controller to call the host:
#RequestMapping("Trainer/reStaff/")
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody response(#RequestParam("trainingId") final int trainingId, HttpServletRequest request)
throws ClientProtocolException, IOException {
String hostname="http://10.120.130.22:9292/";
CloseableHttpClient httpclient = HttpClients.custom().build();
CloseableHttpResponse response=null;
try{
String uri=hostname+"Trainer/reStaff/?trainingId="+trainingId;
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
response = httpclient.execute(httpPost);
String responseData = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode()==200)
System.out.println(responseData+"\n");
else
System.out.println("Error :" + responseData+"\n");
}finally {
httpclient.close();
response.close();
}
But i get the error : HTTP Status 404 - type Status reportmessage description The requested resource is not available.
How do i call the new host from my controller?
I understood how this works. We need to pass the url through httpPost in the service layer :
HttpPost httpPost = new HttpPost(hostUri);
JsonObject jsonResponse = null;
try {
String httpRequestBody = jsonRequestBuilder.build().toString();
logger.info("Request Body: " + httpRequestBody);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(httpRequestBody));
HttpResponse httpResponse = httpClient.execute(httpPost);
logger.debug("Response Status: " + httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
StringBuffer httpResponseBody = new StringBuffer();
while ((line = reader.readLine()) != null) {
httpResponseBody.append(line);
}
logger.info("Response Body: " + httpResponseBody.toString());
JsonReader jsonReader = Json.createReader(new StringReader(httpResponseBody.toString()));
jsonResponse = jsonReader.readObject();
jsonReader.close();
} catch (Exception ex) {
logger.error("Error occurred while invoking POST on ep: " + hostUrl, ex);
} finally {
httpPost.releaseConnection();
}
logger.debug("Exiting");
return jsonResponse;

Session cookies - CookieContainer on stack rather than heap causing issue

I've had a look here
C# WebRequest using Cookies
Multiple WebRequest in same session
Reuse Connection with HttpWebRequest in C#
C# keep session id over httpwebrequest
And that's what I'm doing except I wish to store my CookieContainer as a member (named session_cookie) in my class called connector. My problem is that if I use a temporary object in my code then the cookies work fine:
CookieContainer t = new CookieContainer();
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = t;
But if I use
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = session_cookie;
Then it doesn't work! I cannot figure out why
Here is the connector class code:
public class Connector
{
public CookieContainer session_cookie;
private string session_id;
private HttpWebRequest HTTPReq;
private HttpWebResponse Response;
//Session oriented connection
public string serverRequest(string scriptURL, string payLoad)
{
try
{
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = session_cookie;
HTTPReq.Method = "POST";
//Data arguments
byte[] byteArray = Encoding.UTF8.GetBytes(payLoad);
HTTPReq.ContentType = "application/x-www-form-urlencoded";
HTTPReq.ContentLength = byteArray.Length;
//Get the stream to write into
Stream dataStream = HTTPReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = (HttpWebResponse)HTTPReq.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Western latin alphabet (windows default)
//Get the repsonse from the server
StreamReader ResponseStream = new StreamReader(Response.GetResponseStream(), enc);
string response = ResponseStream.ReadToEnd().Trim();
Response.Close();
ResponseStream.Close();
return response;
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
}
Any ideas?
You are missing a constructor for your Connector class which needs to initialize your CookieContainer property. You should also use a CookieCollection for capturing the cookies from the response and sending to the next request. Something like this should work:
public class Connector
{
public CookieContainer session_cookie;
private CookieCollection cookies;
private string session_id;
private HttpWebRequest HTTPReq;
private HttpWebResponse Response;
public Connector()
{
session_cookie = new CookieContainer();
cookies = new CookieCollection();
}
//Session oriented connection
public string serverRequest(string scriptURL, string payLoad)
{
try
{
HTTPReq = (HttpWebRequest)WebRequest.Create(scriptURL);
HTTPReq.CookieContainer = session_cookie;
HTTPReq.CookieContainer.Add(cookies);
HTTPReq.Method = "POST";
//Data arguments
byte[] byteArray = Encoding.UTF8.GetBytes(payLoad);
HTTPReq.ContentType = "application/x-www-form-urlencoded";
HTTPReq.ContentLength = byteArray.Length;
//Get the stream to write into
Stream dataStream = HTTPReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = (HttpWebResponse)HTTPReq.GetResponse();
cookies = Response.Cookies; // capture cookies from response for next request
Encoding enc = Encoding.GetEncoding(1252); // Western latin alphabet (windows default)
//Get the repsonse from the server
StreamReader ResponseStream = new StreamReader(Response.GetResponseStream(), enc);
string response = ResponseStream.ReadToEnd().Trim();
Response.Close();
ResponseStream.Close();
return response;
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
}

How can I wait end to work async callback HttpWebRequest on Windows Phone 7?

Sorry, it's questions already was on stackoverflow, but I don't found answer. Maybe it's classic, but I can't understand, how to solve this problem :(
I have Singletone class for working with web service:
public sealed class GYAccessService
{
static GYAccessService instance = null;
static readonly object padlock = new object();
public string Atoken { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Uid { get; set; }
const string UrlRequest = "http://site.html";
private GYAccessService()
{
}
public static GYAccessService Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new GYAccessService();
}
return instance;
}
}
}
public void sendPost(string postData)
{
PostData = "request=" + postData;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UrlRequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
webRequest.AllowAutoRedirect = true;
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(getRequestStreamCallback), webRequest);
}
private void getRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(getResponseCallback), webRequest);
}
private void getResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(Response)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceResponse));
ServiceResponse res = (ServiceResponse)serializer.ReadObject(stream);
// I want to return res in main thread
}
}
catch (WebException e)
{
// Error treatment
ServiceResponse err = new ServiceResponse();
err.Message = e.Message;
}
}
public string getRequestString(string model, string method, Params parametrs, string auth = null)
{
Function func = new Function();
func.Model = model;
func.Method = method;
func.Params = parametrs;
ServiceRequest req = new ServiceRequest() { Function = func };
string json = JsonConvert.SerializeObject(req);
ServiceResponse deserializedProduct = JsonConvert.DeserializeObject<ServiceResponse>(json);
return json;
}
}
I have call sendPost() in main thread, I want to return response in this function.
GYAccessService gy = GYAccessService.Instance;
gy.sendPost(postData);
//I want to use the response here
But in WP 7 HttpWebRequest has not GetResponse, only BeginGetResponse. I use callback and don't know how can I return response from callback. I put up with it, I can set property response my Singletone and get it after end async callback, but I don't know how can I block async callback. It's really problem, I try to use WaitOne()/Set() - don't help me, my app just frozen. I try to use IAsyncResult handle, but not success. How can I wait end to work async callback? Thanks in advance!
You need to use the EndGetResponse method and process the result in it. It is asynchronous, so you will not be able to immediately get the result after you call gy.sendPost(postData);, you have to use it as a call back.
If I may suggest, there is a simpler way for such HTTP calls, use RestSharp. It is a great and easy to use library that also works with Windows Phone.

Issues with multipart Post

I am using HttpWebRequest for Multipart Post to upload images in the form of byte array to server and I am supposed to receive a json string containing details of the post in response. But in contrast I am getting just a response code "OK" as the response irrespective of the success or unsuccess of the post. Can anybody help me out for this.
I using following code for the post.
Dictionary<string, object> postParam;
public void SubmitPost()
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));
myRequest.Method = "POST";
myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
public string url
{
get
{
return "URL";
}
}
string boundary = "----------" + DateTime.Now.Ticks.ToString();
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
writeMultipartObject(postStream, postParam);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
string res;
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
streamResponse.Close();
streamRead.Close();
res = response.StatusCode.ToString();
response.Close();
}
the value of res is always "OK"
You need to read response from streamRead. StatusCode is just says that data has been uploaded.

Windows phone 7: post some values, retrieve the response

How can I post a value to an online page, and then retrieve the response to put it in a string?
It's a PHP page that take the $_POST value and then echo a response that I want to grab.
Look at the HttpWebRequest object.
public void DoWork()
{
var url = "http://posttestserver.com/post.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "Username=MyUserName&password=MyPassword";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoWork();
}
his code adapted slightly from this question

Resources