Call external json webservice from asp.net C# - asp.net

I need to make a call to a json webservice from C# Asp.net. The service returns a json object and the json data that the webservice wants look like this:
"data" : "my data"
This is what I've come up with but I can't understand how I add the data to my request and send it and then parse the json data that I get back.
string data = "test";
Uri address = new Uri("http://localhost/Service.svc/json");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}";
How can I add my json data to my request and then parse the response?

Use the JavaScriptSerializer, to deserialize/parse the data. You can get the data using:
// corrected to WebRequest from HttpWebRequest
WebRequest request = WebRequest.Create("http://localhost/service.svc/json");
request.Method="POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}"; //encode your data
//using the javascript serializer
//get a reference to the request-stream, and write the postData to it
using(Stream s = request.GetRequestStream())
{
using(StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
}
//get response-stream, and use a streamReader to read the content
using(Stream s = request.GetResponse().GetResponseStream())
{
using(StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
//decode jsonData with javascript serializer
}
}

Related

Mendeley Pagination

There are currently 1205 resources (citations) in the SciTS Mendeley group. However, no matter how we call the “getDocuments” method of the API, we only get the first 1000 resources. Is there a specific parameter we need to pass to get the full list of resources? Or is there a way to make a subsequent call that gets data pages not returned by the first call?
string grantType = "client_credentials";
string applicationID = "id";
string clientsecret = "XXXXXXX";
string redirecturi = "*******";
string url = "https://api-oauth2.mendeley.com/oauth/token";
string view = "all";
string group_id = "f7c0e437-f68b-34df-83c7-2877147ba8f9";
HttpWebResponse response = null;
try
{
// Create the data to send
StringBuilder data = new StringBuilder();
data.Append("client_id=" + Uri.EscapeDataString(applicationID));
data.Append("&client_secret=" + Uri.EscapeDataString(clientsecret));
data.Append("&redirect_uri=" + Uri.EscapeDataString(redirecturi));
data.Append("&grant_type=" + Uri.EscapeDataString(grantType));
data.Append("&response_type=" + Uri.EscapeDataString("code"));
data.Append("&scope=" + Uri.EscapeDataString("all"));
byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
// Setup the Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
// Write data
Stream postStream = request.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Send Request & Get Response
response = (HttpWebResponse)request.GetResponse();
string accessToken;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
// Retrieve and Return the Access Token
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)ser.DeserializeObject(json);
accessToken = x["access_token"].ToString();
}
// Console.WriteLine("Access TOken"+ accessToken);
var apiUrl = "https://api-oauth2.mendeley.com/oapi/documents/groups/3556001/docs/?details=true&items=1250";
try
{
request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Host = "api-oauth2.mendeley.com";
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
//need this to import documents
}
}
catch (WebException ex1)
{
Console.WriteLine("Access TOken exception" + ex1.Message);
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (HttpWebResponse err = (HttpWebResponse)e.Response)
{
Console.WriteLine("The server returned '{0}' with the status code '{1} ({2:d})'.",
err.StatusDescription, err.StatusCode, err.StatusCode);
}
}
}
The default number of items returned is limited to 1000 per page. For a paginated response you should get some additional fields in the response; notably 'items_per_page','total_pages','total_results'.
I suspect you have will two pages and to get the next result you need to append 'page=1'.

Calling Rest Api with HTTP authentication

I have to call a Rest API securely. I have an authenticate API which returns a token. I need to add this token the API I am calling.
This is the usual way I know of calling the Rest API. I need to append string token to this request.
// *** Establish the request
string token= getAuthenticate(username,password,out token );
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(lcUrl);
// *** Retrieve request info headers
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader loResponseStream = new StreamReader(response.GetResponseStream());
string lcHtml = loResponseStream.ReadToEnd();
response.Close();
loResponseStream.Close();
Not Sure what's the problem... To get the response from the Rest Uri you can do like below :
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(yourUrl + token); // Append Here
request.Method = "GET"; // GET or POST Define Here
//http.Accept = "application/json"; // Add if require
//http.ContentType = "application/json"; // Add if require
String test = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
test = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
Or You can use Simple requests through WebClient:
For Example:
WebClient webClient = new WebClient();
string json = string.Empty;
// Downloads JSon String
json = webClient.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London,uk"); // Replace your URL + Token...
There is third party component also available = RestSharp.
I am using HttpClient, no different at all. I thought this way more clean : http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
var uri = "http://example.com";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token_you_want_to_used);
var response = await httpClient.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();
}

passing custom object after serialization to WCF

I have a WCF service method with following signature:
public string CTNotification(JSONRecordingCompletedNotification content)
{
I want to create a client and consume it. I have written following code but it gives error:
using (StreamReader sr = new StreamReader(Server.MapPath("~/json.txt")))
{
string serviceBaseUrl = ConfigurationManager.AppSettings["serviceurl"].ToString() + "CTNotification";
string conversationId = ConfigurationManager.AppSettings["conversationId"].ToString();
String line = sr.ReadToEnd();
string jsonText = line;
string body = jsonText;
JSONRecordingCompletedNotification RecordingCompletedNotification = new JavaScriptSerializer().Deserialize<JSONRecordingCompletedNotification>(body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceBaseUrl);
request.Method = "POST";
request.ContentType = "application/json";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(RecordingCompletedNotification);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Label1.Text = response.ToString();
}
I get following error:
The remote server returned an error: (400) Bad Request.
i would suggest you to use either of the lib for json serialization and deserialization
json.net
fastjson
and change the content type as
request.ContentType = "application/json; charset=utf-8";

How to dynamically invoke Web Services in .Net

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.
I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.
I have found a couple of posts where this is accomplished compiling dynamically the Proxy class.
But for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.
In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(
#"<?xml version='1.0' encoding='utf-8'?>
<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'>
<soap12:Body>
<HelloWorld xmlns='http://tempuri.org/' />
</soap12:Body>
</soap12:Envelope>");
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:
using (var serviceProxy = new ServiceProxy())
{
serviceProxy.Url = somepropertysetbythewebpart;
// make call to method here
}
After a lot of resarching I found out how to do it. The code of the selected answer is almost there, but I had to add the SOAPAction in the header and also change the ContentType.
Here is the entire code:
var strRequest = #"<soap12:Envelope>
...
</soap12:Envelope>";
string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");
byte[] data = Encoding.UTF8.GetBytes(strRequest);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();
return new HttpResponseMessage()
{
Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

How to post an XML file or data to a URL using httpWebRequest and httpWebResponse?

I need to post the XML data which I will get from the database, to a URL like ... http://www.rentals.com/aspx ... using ASP.NET
you can write a function like this:
private string SendRequest(Uri UriObj, string data)
{
string _result;
var request = (HttpWebRequest) WebRequest.Create(UriObj);
request.Method = "POST";
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
var response = (HttpWebResponse) request.GetResponse();
var streamResponse = response.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
_result = streamRead.ReadToEnd().Trim();
streamRead.Close();
streamResponse.Close();
response.Close();
return _result;
}
The string data can be XML like "<xmla><..></..></xmla>" on .aspx page to get the data, you need to use Request.InputStream and read the stream into string, XML, etc...

Resources