Session cookies - CookieContainer on stack rather than heap causing issue - session

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;
}
}
}

Related

How to convert collection to csv with jackson in java spring?

I have a problem to convert a java.util.Collection to a csv file with jackson.
In the following code you can see a method to convert the collection to a csv-string.
But i need a method to convert the collection with com.fasterxml.jackson.
The Enum "DownloadType" get the column and headerlines for csv file.
Do you have an idea to fix them?
#RequestMapping(value = "/csv",
produces = {"text/csv"},
consumes = {"application/json"},
method = RequestMethod.POST)
public ResponseEntity<Object> exportCsv()
{
ResponseEntity<Object> response = null;
try
{
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "text/csv; charset=UTF-8");
headers.add(HttpHeaders.CACHE_CONTROL, "no-store, must-revalidate");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"export.csv\"");
headers.add(HttpHeaders.EXPIRES, "0");
byte[] csvBytes = null;
byte[] headerBytes = null;
byte[] lineBytes = null;
CsvMapper mapper = new
Collection<User> users = getUsers()
headerBytes = DownloadType.USER.getHeaderLine().getBytes("UTF-8");
lineBytes = mapper.writer(DownloadType.USER.getCsvSchema()).writeValueAsBytes(users);
if (headerBytes != null && lineBytes != null)
{
csvBytes = new byte[headerBytes.length + lineBytes.length];
System.arraycopy(headerBytes, 0, csvBytes, 0, headerBytes.length);
System.arraycopy(lineBytes, 0, csvBytes, headerBytes.length, lineBytes.length);
}
response = new ResponseEntity<>(csvBytes, headers, HttpStatus.OK);
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
}
return response;
}
Maybe try something like this. By writing the data directly to the servlet response the string will get returned directly back to the client as is without formatting or post-processing.
#RequestMapping(value = "/csv",
produces = {"text/csv"},
consumes = {"application/json"},
method = RequestMethod.POST)
public void exportCsv(HttpServletResponse response)
{
...
String headerString = DownloadType.USER.getHeaderLine()
String data = mapper.writer(DownloadType.USER.getCsvSchema()).writeValueAsString(users);
response.setContentType("text/plain; charset=utf-8");
response.getWriter().print(headerString);
response.getWriter().print(data);
Adapted from:
How to Return CSV Data in Browser From Spring Controller

Request & Response Windows Phone

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

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