How to get json data in REST endpoint C# - c#

i set the Transaction response callback url of an API to : https://requestb.in/st4fz3st and it gives me a response ok, on debugging the response process by checking the link https://requestb.in/st4fz3st?inspect the results shown in the image below.
i want to get the json data so i wrote this c# code
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
return errorText;
}
throw;
}
}
protected void Page_Load(object sender, EventArgs e)
{
x = GET(" https://requestb.in/st4fz3st");
Response.Write(x);
}
But what i get is the ok not the RAW BODY which is marked in red.

You can use the api. For example in your case: https://requestb.in/api/v1/bins/st4fz3st/requests
You can parse the result with Newtonsoft.Json. The 'raw body' is body property

Related

C# get api response for debugging

I am trying to get api response based on apiurl as parameter using c# code as below. Things are working fine but I am unable to debug and see the final json response. Is there any other option to get the api response to a variable to debug and check final complete response. Will this approach of getting api json has any issues?
[HttpGet("[action]")]
public async Task<string> GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", BearerToken);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
throw;
}
}

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

c# catch empty Json / 404 error

I have the following code for accessing a Api which returns a Json value. Now it's possible that i try to access the api but nothing is being returned, aka the given ID its trying to search doesnt exist. This ofcourse returns a 404 but i do not know how to handle this error so the code continious on going, now it breaks the program and crashes.
public RootObject GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()){
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
catch (WebException ex){
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()){
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
This is the button click event where the Url of the api is given.
private void button1_Click(object sender, EventArgs e)
{
result_rTBox.Text = "";
api_Handler api_Handler = new api_Handler();
string spidyApi_itemSearch = "http://www.gw2spidy.com/api/v0.9/json/item-search/";
string Gw2Api_allListings = "https://api.guildwars2.com/v2/commerce/listings/";
string userInput_itemName = userSearchInput_tBox.Text;
string spidyApi_searchIdByName = spidyApi_itemSearch + userInput_itemName;
if (!string.IsNullOrWhiteSpace(userSearchInput_tBox.Text)){
var spidyApi_searchIdByName_result = api_Handler.GetApi(spidyApi_searchIdByName);
var Gw2Api_isItemIdinListing_result = api_Handler.GetApi(Gw2Api_allListings + spidyApi_searchIdByName_result.results[0].data_id);
//result_rTBox.Text = Gw2Api_isItemIdinListing_result.results[0].data_id.ToString();
}
}
First i access the api with string "spidApi_itemSearch" and after that I have and ID that i need to check if exists in the api Gw2Api_allListings. If it doesnt exist, which will happen quite often, it returns nothing with a 404 error. How do i get around of making the code continue even if it returns nothing?
EDIT: code that i have now, still crashes on the break.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
var requesting = WebRequest.Create(url);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound){
}
}
throw;
}
}
Use the HttpStatusCode Enumeration, specifically HttpStatusCode.NotFound
Instead of WebResponse, try using HttpWebResponse
HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
// handle the error here
}
Where we is a WebException

Web service request time out issue

I want to interact with a web service, and for this purpose I am using this code.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"http://192.168.2.51/loodappSrv/LoodAppsrv.svc/company/insertcompany?Validation_Token=dc6f3d5e-22c7-405f-abb6-4491de140e7e");
req.Method = "POST";
req.ContentType = #"text/json";
JsonComapnyFormat jcf = new JsonComapnyFormat();
string data = jcf.data();//data in json Format {"companyName":"Alpha","departmentId":3}
using (Stream requestStream = req.GetRequestStream())
{
StreamWriter streamWriter = null;
try
{
//streamWriter = new StreamWriter(requestStream, System.Text.Encoding.Default);
streamWriter = new StreamWriter(requestStream, System.Text.Encoding.Default);
streamWriter.Write(data);
}
catch (Exception ex)
{
throw ex;
}
finally
{
try
{
streamWriter.Close();
requestStream.Close();
streamWriter.Dispose();
streamWriter = null;
requestStream.Dispose();
}
catch
{
}
}
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
ViewBag.ABC = result;
return View();
If I Use Fiddler to send POST data on the given URL, it is perfect (sudden response comes out). But when I send same date on the same URL then the message return in an exception "The operation has timed out" at HttpWebResponse response = (HttpWebResponse)req.GetResponse();. Please suggest solutions.
Have you tried what SLaks mentioned ?
The MIME media type for JSON text is application/json.
As can be seen here

Sending xml using Apache HttpComponents

I am attempting to replicate the following C# code in Java. This code is a helper class that sends a request containing xml, and reads a response.
internal static String Send(String url, String body)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
try
{
// create the new httpwebrequest with the uri
request.ContentLength = 0;
// set the method to POST
request.Method = "POST";
if (!String.IsNullOrEmpty(body))
{
request.ContentType = "application/xml; charset=utf-8";
byte[] postData = Encoding.Default.GetBytes(body);
request.ContentLength = postData.Length;
using (Stream s = request.GetRequestStream())
{
s.Write(postData, 0, postData.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
String responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ResponseException(((int)response.StatusCode),
response.StatusCode.ToString(), request.RequestUri.ToString(),
responseString);
}
return responseString;
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = response as HttpWebResponse;
if (httpResponse != null)
{
using (Stream data = response.GetResponseStream())
{
data.Position = 0;
throw new ResponseException(((int)httpResponse.StatusCode),
httpResponse.StatusCode.ToString(), request.RequestUri.ToString(),
new StreamReader(data).ReadToEnd()
);
}
}
else
{
throw;
}
After reading other threads I determined that the Apache HttpComponents library would be my best bet to get the same functionality. After reading the documentation and following the example here:
http://hc.apache.org/httpcomponents-client-ga/quickstart.html
I am unable to figure out how to send the body string as xml. When I attempt to set the entity for the request it requires that I declare a BasicNameValuePair, and I do not understand what this is, or how I would format the body string to meet this specification.
Below is what I have currently done.
protected static String Send(String url, String body)
{
HttpPost request = new HttpPost(url);
try
{
request.setHeader("ContentType", "application/xml; charset=utf=8");
// Encode the body if needed
request.setEntity(new UrlEncodedFormEntity());
//get the response
// if the response code is not valid throw a ResponseException
// else return the response string.
} finally {
request.releaseConnection();
}
return null;
}
EDIT : or should I use a StringEntity and do the following
protected static String SendToJetstream(String url, String body)
{
HttpPost request = new HttpPost(url);
try
{
StringEntity myEntity = new StringEntity(body,
ContentType.create("application/xml", "UTF-8"));
// Encode the body if needed
request.setEntity(myEntity);
//get the response
// if the response code is not valid throw a ResponseException
// else return the response string.
} finally {
request.releaseConnection();
}
return null;
}
Use a FileEntity
File file = new File("somefile.xml");
FileEntity entity = new FileEntity(file, ContentType.create("application/xml", "UTF-8"));
Lots of good examples here: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e165

Categories

Resources