Getting exception Newtonsoft.Json.JsonReaderException - c#

I request for gZip response in Header like :
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
In webresponse I am getting ContentEncoding = gzip
I don't know how to decompress gzip response with my code and when I read the string with json I getting Newtonsoft.Json.JsonReaderException
What is the solution ?
using (WebResponse response = GetWebResponse(request))
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
This is how I construct request :
var request = CreateWebRequest(new Uri(uri), type);
// create request stream from arguments
if (args != null)
{
string requestData = string.Empty;
requestData = Newtonsoft.Json.JsonConvert.SerializeObject(args, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.GetEncoding("UTF-8").GetBytes(requestData);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
protected WebRequest CreateWebRequest(Uri uri, MethodType type, bool IsUrlEncoded = false)
{
WebRequest request = WebRequest.Create(uri);
(request as HttpWebRequest).Accept = "application/json";
System.Net.ServicePointManager.Expect100Continue = false;
if (IsUrlEncoded)
request.ContentType = "application/x-www-form-urlencoded";
else
request.ContentType = "application / json";
request.Headers.Add("X-Application", AppKeyData.Appkey);
if (!string.IsNullOrEmpty(AppKeyData.SessionToken))
{
request.Headers.Add("X-Authentication", AppKeyData.SessionToken);
}
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
request.Method = type.ToString();
return request;
}

You have to set AutomaticDecompression property on your request.
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Update:
You can include below line in your CreateWebRequest method.
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

Related

C# - Receiving strange character from HttpWebResponse

I have this code to send a HTTP Request:
public string MakeRequest(string requestUrl, object data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/json";
request.KeepAlive = false;
request.Headers.Add("Authorization", "BEARER " + apiToken);
System.Net.ServicePointManager.Expect100Continue = false;
if (data != null)
{
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(data);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
else
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
string Charset = response.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
return reader.ReadToEnd();
}
}
It works well for most calls but one POST where I receive this as response:
"�\b\0\0\0\0\0\0�V�M,.I-�/JI-R��V3<S����L�L,�L��jk[���&\0\0\0"
And when I see the call captured by Fiddler it says the routine received:
{
"MasterOrder": {
"OrderId": "65250824"
}
}
So, what is happening exactly? How is that Fiddler sees one response and the applications sees another response?
Solved the issue by adding these lines to the request:
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

How to shim HttpWebRequest Headers?

I am trying to Shim the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + authToken.token.access_token);
request.Accept = "application/json";
But running the Unit Test throws an exception in this part: request.Headers.Add() because request.Headers is null. This, in spite of initializing Headers in my test:
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => {
request.Instance.Headers = new WebHeaderCollection {
{"Authorization", "Bearer abcd1234"}
};
//also tried initilizing it like this:
//WebHeaderCollection headers = new WebHeaderCollection();
//headers[HttpRequestHeader.Authorization] = "Bearer abcd1234";
//request.Instance.Headers = headers;
return request.Instance;
};
But request.Instance.Headers is still null.
What am I missing?
I solved this by creating a getter for Headers so that it would return a WebHeaderCollection instead of null.
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => request.Instance;
request.HeadersGet = () => {
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer abcd1234");
return headers;
};
I solved this by instantiating Header property of ShimHttpWebRequest as follows,
var httpWebRequest = new ShimHttpWebRequest() { HeadersGet = () => new WebHeaderCollection() };
ShimWebRequest.CreateString = (arg1) => httpWebRequest.Instance;
This is my code, you can try it:
public static string HttpPostWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string msg)
{
msg = string.Empty;
string result = string.Empty;
try
{
byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = requestUrl;
request.Method = isPost ? "POST" : "GET";
request.ContentLength = bytes.Length;
request.Timeout = timeout * 1000;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
result = reader.ReadToEnd();
reader.Close();
responseStream.Close();
request.Abort();
response.Close();
return result.Trim();
}
}
catch (Exception ex)
{
msg = ex.Message + ex.StackTrace;
}
return result;
}

Add param POST request using HttpWebRequest async windows phone 8 - JSON [duplicate]

I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()

How to get value back from a web services in C#?

I am sending a URL and XML to a webservices, so that it will return me JSON about the result. I am here posting the request to the webservices how do I get the value from the webservices back. The value returned by the webservices is JSON. What should be the return type here and what should be returned to get the HTTP response status and body
public string HttpPostcredentials(string XML, string url)
{
try
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
req.ContentType = "application/xml";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
}
catch (Exception e)
{
}
return null;
}
Is this what you are looking for:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = "POST";
}
byte[] requestBodyBytes = Encoding.ASCII.GetBytes(XML);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
You need to get the Response from the HttpWebRequest
WebResponse result = req.GetResponse();

How to add parameters into a WebRequest?

I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()

Categories

Resources