400 Bad request on c# code - c#

Getting an error exception thrown on this small piece of code but I can't figure out why / where. Fairly new to this so any help would be apprecaited
private void GetServiceData(string url)
{
try
{
if (!string.IsNullOrEmpty(this.Service) && !string.IsNullOrEmpty(url))
{
string data = string.Empty;
string name = string.Format("{0}Data", this.Service);
using (WebClient client = new WebClient())
{
data = client.DownloadString(url);
}
Page.ClientScript.RegisterHiddenField(name, data);
}
}
catch (Exception ex)
{
Shared.Utilities.ExceptionLog.WriteExceptionToLog(ex, "CourseFinderServiceControl.GetServiceData()");
}
}

If this is for Twitch, you need to specify client when requesting the data.

Related

Checking if URL is valid without downloading the file in c#

I'm trying to check is a given URL is Valid and downloadable.
I wrote this code and it does work but i'm wondering if it can be achieved without the ugly try-catch
public static bool IsUrlValid(string url)
{
try
{
WebClient webClient = new WebClient();
var stream = webClient.OpenRead(url);
return true;
}
catch (Exception ex)
{
return false;
}
}

Download vimeo video through its URL

I am trying to achieve this for vimeo videos through C# code, but the file being downloaded is the HTML. Can someone tell me how to do this? Below you can find the two handlers I implemented. Both have the same behaviour that I already described.
Handle.GET("/testDownload", (Request r) =>
{
Response response = 0;
try
{
WebClient webClient = new WebClient();
webClient.DownloadFile("https://player.vimeo.com/video/140308351", #"c:\binte\test");
}
catch (Exception ex)
{
GlobalDictionary.errorLog.LogError("Error in test download handler : " + ex.Message);
}
response.Body = "success";
return response;
}, new HandlerOptions() { SkipMiddlewareFilters = true });
Handle.GET("testDownloadVideo?url={?}", (string url, Request r) =>
{
Response response = 0;
string fileName = "testDownload.mpeg";
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.DownloadFileAsync(new Uri(url), fileName);
}
}
catch (Exception ex)
{
GlobalDictionary.errorLog.LogError("Error in test download handler : " + ex.Message);
}
response.Body = "success";
return response;
}, new HandlerOptions() { SkipMiddlewareFilters = true });
EDIT: After some research, I think this is not possible to be done, unless I would be the owner of the video, and therefore able to use the API for that purpose. I will leave the question open though, one day this might change.

How to catch exception?

I am trying to call api and check its response, but when ever some wrong value is passed it stops the program. I want to add exception during request and response but not sure how to write in function.
This is how i call my REST call
public dynamic APICalls(JObject ljson, string endpoints, string method)
{
var httpReq = (HttpWebRequest)HttprequestObject(endpoints, method);
using (var streamWriter = new StreamWriter(httpReq.GetRequestStream()))
{
streamWriter.Write(ljson);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
var result = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
THis is code for request
public dynamic HttprequestObject(string endpoints, string method)
{
string url = Settings.API_TEST_VALUE + endpoints;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method;
return httpWebRequest;
}
And right before request and right after response i want to catch exception.
At this point i have to catch exception
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
If some one gives me hint how to catch that before it stops program.
There are 400, 401,402 errors, if something is wrong API sends json
For instance, while creating user :-- Email id already exists
But that points stops json and stops program..
Using try catch it will stop program, I want it to run and want to receive resposne.
Actually, API will send error .
For instance, status will be ;---401 UNAUTHORIZED
and resposnse will be
{ "reason": "Email already registered.", "success": false }
I am changed my code and
HttpWebResponse httpResponse;
try
{
//HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpReq.GetResponse();
httpResponse = (HttpWebResponse)httpReq.GetResponse();
//myHttpWebResponse.Close();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
//return "Success";
//not sure what to return
//here i have to add sql server code to enter into database
}
This is the new code, but I m not getting Json as return value, So i can show specific error.
For below Json what should I write?
{ "reason": "Email already registered.", "success": false }
please I m new to c# and if something is not clear please modify or ask question?
thank you
What you're looking for is called a try-catch statement:
try
{
var httpResponse = (HttpWebResponse)httpReq.GetResponse();
}
catch (WebException e)
{
// Here is where you handle the exception.
}
Using WebException as the type in the catch statement means only exceptions of that particular type will be caught.
In case an exception occurs, the e variable will contain exception details, such as a message passed from the method which three the exception and any inner exceptions encapsulated inside.
You can handle your web exceptions to get HttpStatusCode and Response Message this way:
public void SendAndGetResponseString()
{
try
{
// Here you call your API
}
catch (WebException e)
{
var result = GetResponceFromWebException(e);
if (result != null){
//
// Here you could use the HttpStatusCode and HttpResponseMessage
//
}
throw;
}
catch (Exception e)
{
// log exception or do nothing or throw it
}
}
private HttpRequestResponce GetResponceFromWebException(WebException e)
{
HttpRequestResponce result = null;
if (e.Status == WebExceptionStatus.ProtocolError)
{
try
{
using (var stream = e.Response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var responseString = reader.ReadToEnd();
var responce = ((HttpWebResponse) e.Response);
result = new HttpRequestResponce(responseString, responce.StatusCode);
}
}
}
}
catch (Exception ex)
{
// log exception or do nothing or throw it
}
}
return result;
}
public class HttpRequestResponce {
public HttpStatusCode HttpStatusCode { get;set; }
public string HttpResponseMessage {get;set;}
public HttpRequestResponce() { }
public HttpRequestResponce(string message, HttpStatusCode code)
{
HttpStatusCode=code;
HttpResponseMessage=message;
}
}
You encapsulate whatever method call or code block you want to prevent from throwing unhandled exceptions.
try
{
// code here
}
catch (Exception)
{
// here you may do whatever you want to do when an exception is caught
}
Ok,Finally I am able to Solve this.. Thanks everyone for you help.
This worked for me. I think I was not reading whole response.. So some how I think I realized and now its working ..
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Exception handling the right way for WebClient.DownloadString

I was wondering what exceptions I should protect myself against when using WebClient.DownloadString.
Here's how I'm currently using it, but I'm sure you guys can suggest better more robust exception handling.
For example, off the top of my head:
No internet connection.
Server returned a 404.
Server timed out.
What is the preferred way to handle these cases and throw the exception to the UI?
public IEnumerable<Game> FindUpcomingGamesByPlatform(string platform)
{
string html;
using (WebClient client = new WebClient())
{
try
{
html = client.DownloadString(GetPlatformUrl(platform));
}
catch (WebException e)
{
//How do I capture this from the UI to show the error in a message box?
throw e;
}
}
string relevantHtml = "<tr>" + GetHtmlFromThisYear(html);
string[] separator = new string[] { "<tr>" };
string[] individualGamesHtml = relevantHtml.Split(separator, StringSplitOptions.None);
return ParseGames(individualGamesHtml);
}
If you catch WebException, it should handle most cases. WebClient and HttpWebRequest throw a WebException for all HTTP protocol errors (4xx and 5xx), and also for network level errors (disconnection, host not reachable, etc)
How do I capture this from the UI to show the error in a message box?
I'm not sure I understand your question... Can't you just show the exception message?
MessageBox.Show(e.Message);
Don't catch the exception in FindUpcomingGamesByPlatform, let it bubble up to the calling method, catch it there and show the message...
I usually handle it like this to print any exception message the remote server is returning. Given that the users are allowed to see that value.
try
{
getResult = client.DownloadString(address);
}
catch (WebException ex)
{
String responseFromServer = ex.Message.ToString() + " ";
if (ex.Response != null)
{
using (WebResponse response = ex.Response)
{
Stream dataRs = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataRs))
{
responseFromServer += reader.ReadToEnd();
}
}
}
_log.Error("Server Response: " + responseFromServer);
MessageBox.Show(responseFromServer);
}
I use this code:
Here I init the webclient whithin the loaded event
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
// download from web async
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://whateveraurisingis.com"));
}
The callback
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
#region handle download error
string download = null;
try
{
download = e.Result;
}
catch (Exception ex)
{
MessageBox.Show(AppMessages.CONNECTION_ERROR_TEXT, AppMessages.CONNECTION_ERROR, MessageBoxButton.OK);
}
// check if download was successful
if (download == null)
{
return;
}
#endregion
// in my example I parse a xml-documend downloaded above
// parse downloaded xml-document
var dataDoc = XDocument.Load(new StringReader(download));
//... your code
}
Thanks.
According to the MSDN documentation, the only non-programmer exception is WebException, which can be raised if:
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.

How to post data to specific URL using WebClient in C#

I need to use "HTTP Post" with WebClient to post some data to a specific URL I have.
Now, I know this can be accomplished with WebRequest but for some reasons I want to use WebClient instead. Is that possible? If so, can someone show me some example or point me to the right direction?
I just found the solution and yea it was easier than I thought :)
so here is the solution:
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
it works like charm :)
There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:
using(WebClient client = new WebClient())
{
var reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("param1", "<any> kinds & of = ? strings");
reqparm.Add("param2", "escaping is already handled");
byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
Using WebClient.UploadString or WebClient.UploadData you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.
byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
string sret = System.Text.Encoding.ASCII.GetString(bret);
More: http://www.daveamenta.com/2008-05/c-webclient-usage/
string URI = "site.com/mail.php";
using (WebClient client = new WebClient())
{
System.Collections.Specialized.NameValueCollection postData =
new System.Collections.Specialized.NameValueCollection()
{
{ "to", emailTo },
{ "subject", currentSubject },
{ "body", currentBody }
};
string pagesource = Encoding.UTF8.GetString(client.UploadValues(URI, postData));
}
//Making a POST request using WebClient.
Function()
{
WebClient wc = new WebClient();
var URI = new Uri("http://your_uri_goes_here");
//If any encoding is needed.
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//Or any other encoding type.
//If any key needed
wc.Headers["KEY"] = "Your_Key_Goes_Here";
wc.UploadStringCompleted +=
new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");
}
void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch(Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Using simple client.UploadString(adress, content); normally works fine but I think it should be remembered that a WebException will be thrown if not a HTTP successful status code is returned. I usually handle it like this to print any exception message the remote server is returning:
try
{
postResult = client.UploadString(address, content);
}
catch (WebException ex)
{
String responseFromServer = ex.Message.ToString() + " ";
if (ex.Response != null)
{
using (WebResponse response = ex.Response)
{
Stream dataRs = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataRs))
{
responseFromServer += reader.ReadToEnd();
_log.Error("Server Response: " + responseFromServer);
}
}
}
throw;
}
Using webapiclient with model send serialize json parameter request.
PostModel.cs
public string Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
WebApiClient.cs
internal class WebApiClient : IDisposable
{
private bool _isDispose;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (!_isDispose)
{
if (disposing)
{
}
}
_isDispose = true;
}
private void SetHeaderParameters(WebClient client)
{
client.Headers.Clear();
client.Headers.Add("Content-Type", "application/json");
client.Encoding = Encoding.UTF8;
}
public async Task<T> PostJsonWithModelAsync<T>(string address, string data,)
{
using (var client = new WebClient())
{
SetHeaderParameters(client);
string result = await client.UploadStringTaskAsync(address, data); // method:
//The HTTP method used to send the file to the resource. If null, the default is POST
return JsonConvert.DeserializeObject<T>(result);
}
}
}
Business caller method
public async Task<ResultDTO> GetResultAsync(PostModel model)
{
try
{
using (var client = new WebApiClient())
{
var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
var response = await client.PostJsonWithModelAsync<ResultDTO>("http://www.website.com/api/create", serializeModel);
return response;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Most of the answers are old. Just wanted to share what worked for me. In the interest of doing things asynchronously i.e. to post data to specific URL using WebClient asynchronously in .NET 6.0 Preview 7, .NET Core and other versions can be done using WebClient.UploadStringTaskAsync Method.
Use namespace System.Net; and for a class ResponseType to capture the response from the server, we can use this method to POST data to a specific URL. Make sure to use the await keyword while calling this method
public async Task<ResponseType> MyAsyncServiceCall()
{
try
{
var uri = new Uri("http://your_uri");
var body= "param1=value1&param2=value2&param3=value3";
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.Authorization] = "yourKey"; // Can be Bearer token, API Key etc.....
wc.Headers[HttpRequestHeader.ContentType] = "application/json"; // Is about the payload/content of the current request or response. Do not use it if the request doesn't have a payload/ body.
wc.Headers[HttpRequestHeader.Accept] = "application/json"; // Tells the server the kind of response the client will accept.
wc.Headers[HttpRequestHeader.UserAgent] = "PostmanRuntime/7.28.3";
string result = await wc.UploadStringTaskAsync(uri, body);
return JsonConvert.DeserializeObject<ResponseType>(result);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Here is the crisp answer:
public String sendSMS(String phone, String token) {
WebClient webClient = WebClient.create(smsServiceUrl);
SMSRequest smsRequest = new SMSRequest();
smsRequest.setMessage(token);
smsRequest.setPhoneNo(phone);
smsRequest.setTokenId(smsServiceTokenId);
Mono<String> response = webClient.post()
.uri(smsServiceEndpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(smsRequest), SMSRequest.class)
.retrieve().bodyToMono(String.class);
String deliveryResponse = response.block();
if (deliveryResponse.equalsIgnoreCase("success")) {
return deliveryResponse;
}
return null;
}

Categories

Resources