jeudi 2 avril 2015

Get JSON result from c# web service request


Vote count:

0




This is my web service I have this method:



public bool GetSomeData()
{
try
{
string sURL = GetWebServiceURL();

if (!String.IsNullOrEmpty(sURL))
{
string webServiceResponse = GetWebServiceResponse(sURL);

//do some code

return true;
}
}
catch (Exception ex)
{ }
return false;
}

private string GetWebServiceResponse(string url)
{
string jsonResp = null;

if (!String.IsNullOrEmpty(url))
{
var data = new StringBuilder();
data.Append("param1=value1");
data.Append("&param2=value2");

var request = (HttpWebRequest)WebRequest.Create(url);
var postData = Encoding.UTF8.GetBytes(data.ToString());

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Accept = "application/json, text/javascript, */*; q=0.01";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36";
request.ContentLength = data.Length;
request.Timeout = 5000;

using (var stream = request.GetRequestStream())
stream.Write(postData, 0, postData.Length);


var response = (HttpWebResponse)request.GetResponse();

using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
jsonResp = reader.ReadToEnd();
}

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}

return jsonResp;
}


When I call GetWebServiceResponse() method I need to call a REST web service method (in other web service and url) and get the json object it returns. However the jsonResp variable is always equals to "" (empty string).


What is wrong in my request?


If I do this in JS (with code below) it works, but I need to do the same in my web service for other situations.



function GetSomeData(wsURL){

$.ajax({
type: 'POST',
dataType: "json",
url: wsURL,
timeout: 5000,
data: JSON.stringify({
"param1" : "value1",
"param2" : "value2"
}),

success: function(data) {
jsonResp = data;
}
});
}


I already read many things like this but I can't solve my problem. Can anyone help me?



asked 1 min ago

Ninita

397






Get JSON result from c# web service request

Aucun commentaire:

Enregistrer un commentaire