In my program I need to get the content of my site, however the return of DownloadString method of the webclient object returns null, however the most intriguing is that there is no exception. the status code is 200, the request is made perfectly, but the url returns an empty string.
WebClient wc = new WebClient();
String teste = wc.DownloadString("http://www.wiplay.com.br");
My site
http://www.wiplay.com.br
Seems like your website requires the user agent header to be set in order to respond.
Add the following before your call the DownloadString method:
wc.Headers.Add(HttpRequestHeader.UserAgent, "your useragent string");
In my case use of HttpClient and WebClient resulted in empty string despite status code 200 no matter what headers I set.
If somebody still suffers to this problem,using RestSharp like finally returned expected response body.
var dataString = JObject.FromObject(anonymousObject).ToString();
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddParameter("application/json", dataString, ParameterType.RequestBody);
var response = client.Post(request);
Related
Currently trying to do a Get request as part of a c# program. The request works fine on Postman as it uses a header for authorization. However I cannot get the code working for the program to use this header correctly in its Get request. I've had a good look around and tried various bits of code I've found but haven't managed to resolve it so any help would be appreciated!
public string Connect()
{
using (WebClient wc = new WebClient())
{
string URI = "myURL.com";
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";//this is the entry code/key
string HtmlResult = wc.DownloadString(URI);
return HtmlResult;
}
}
Above is one method inside the class.
Below is another attempt which is an extension method that gets passed the URL:
public static string GetXml(this string destinationUrl)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = "GET";
request.Headers[HttpRequestHeader.Authorization] = "Bearer
OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new
StreamReader(responseStream).ReadToEnd();
return responseStr;
}
else
{
Console.Write(String.Format("{0}({1})",
response.StatusDescription, response.StatusCode));
}
return null;
}
Might I recommend the very handy RestSharp package (find it on Nuget).
It turns your current code into something like
public string Connect()
{
var client = new RestClient();
var request = new RestRequest("myURL.com", Method.GET);
request.AddParameter("Authorization", "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3");
var response = client.Execute(request);
return response.Content;
}
It's much more succinct and easier to use (in my opinion) and thus lessens the likelihood of passing in or using incorrect methods.
If you're still having issues getting data back/connecting. Then using PostMan click Code in the upper right of PostMan and select the C# (RestSharp) option. Whatever is generated there matches exactly what PostMan is sending. Copy that over and you should get data back that matches your PostMan request.
I Write one application to access one Webservice Restful using C#, i get the Token with success, i access other services without parameters fine, but when i need to send parameters in POST method it´s not work.
In other side, the Wesbservice dont see my post.
Can someone help-me about this ?
Here is my code.
string urlMethod = metodo;
// "/api/v1/organizacao/criar";
var accessToken = IntegraPb.GetToken();
var client = new RestClient(Sincronizador.Properties.Settings.Default.apiUrl);
var request = new RestRequest(urlMethod, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + accessToken);
var jsserie = new System.Web.Script.Serialization.JavaScriptSerializer();
// obj is my class to serialize
request.AddJsonBody(jsserie.Serialize(obj));
IRestResponse response = client.Execute(request);
This image is the request object
AddJsonBody receives a object, not a serialized string of your object. It does the serialization internally.
So use this instead:
request.AddJsonBody(obj);
I'm using RestClient and redirecting the request to external REST webservice (java) as RestRequest. I'm getting HTTP statuscode 'not acceptable' and also the repsonse.content is something like this "The resource cannot be displayed because the file extension is not being accepted by your browser."
the operation is successful but not able to get the required response which is nothing but a string value.
below is code snippet:
var client = new RestClient();
client.BaseUrl = JavaWSURI;
var request = new RestRequest();
//request.AddHeader("Content-Length", int.MaxValue.ToString());
//request.AddHeader("Content-Type", "text/html; charset=utf-8");
// jsonD is JSON input object
request.AddParameter("application/json", jsonD, ParameterType.RequestBody);
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
// The server's Rest method will probably return something
var response = client.Execute(request) as RestResponse;
From the error message, it sounds like you may need to add an 'Accept' header to the request
Add an Accept request header as follows:
request.AddHeader("Accept",
"text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8");
Please note you may need to change the value depending on your content.
I'm having issues making POST requests with RestSharp. My Hashtable object 'param' contains key-value pairs that must be posted to the server. I've tried several combinations and have gotten weird output on the server-side.
Example 1:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);
Output:
Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}
Example 2:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
request.RequestFormat = DataFormat.Json;
request.AddParameter ((entry.Key.ToString()), entry.Value);
}
Output:
Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}
The output for #2 seems correct, but I'm getting a 401 on the server-side. Weirdly, the GET output matches that of #2, but the request is made successfully. I think the problem may be that the request, in total, is posting 10 parameters yet it should be posting one JSON formatted string in the body. Typically, I would put a JSON formatted string in the body, but even when I use a standalone JSON serializer to obtain a JSON string of the Hashtable and put in AddBody, I get the following:
Example 3:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);
Output:
Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}
I'm mostly curious as to why the JSON string that RestSharp is creating contains "_json" at the beginning of it.
Thanks,
John
Is your server running Rails? Maybe this is relevant https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak
If you have control of the server side, might be better to use AddParameter and pass a JSON string, which you can parse on the server side.
I'm trying to update token, but I get error "The remote server returned an error: (400) Bad Request."
My code is:
public static object Refresh_token(string client_id, string redirect_uri, string client_secret, string refresh_token, string scope)
{
var requestUrl = new StringBuilder("https://login.live.com/oauth20_token.srf");
requestUrl.Append("?grant_type=refresh_token");
requestUrl.AppendFormat("&client_id={0}", client_id);
requestUrl.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(redirect_uri));
requestUrl.AppendFormat("&client_secret={0}", HttpUtility.UrlEncode(client_secret));
requestUrl.AppendFormat("&refresh_token={0}", refresh_token);
WebRequest request = HttpWebRequest.Create(requestUrl.ToString());
request.Method = "GET";
request.ContentType = "application/x-www.form-urlencoded;charset=UTF-8";
WebResponse response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
var json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<Offline_access>(json);
}
}
If I send it from browser I get
{"error":"invalid_scope","error_description":"The provided request must include a 'scope' input parameter."}
I tried to do it with POST, but it was the same problem.
Have some ideas?
Seems like the spec changed on the web server side and it's expecting you to send a scope parameter. I don't know what the scope parameter is and what you need to supply to it but essentially you'll need to add a line for the requestUrl to add it.
requestUrl.AppendFormat("&scope={0}", {whatever value the scope is suppose to be});