GetResponse() in API call causes (400) Bad Request error - c#

I am very new to programming.
I'm setting up a loop that continuously send a POST request to a site through the REST API. The POST request works properly and the way I intend.
I would like to add functionality that requires the response from this post. However, every way of retrieving the response gives me an error:
"An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (400) Bad Request."
As I debug line by line, it seems that the "GetResponse()" line causes this each time, and causes the program to break. If I remove this line, the program works properly and throws no errors.
Hoping someone can assist. Here is what I have written:
string URL= "https:.......";
HttpWebRequest apiCall = (HttpWebRequest)WebRequest.Create(airWatchURL);
apiCall.Method = "POST";
apiCall.Headers.Add(HttpRequestHeader.Authorization, auth);
apiCall.Headers.Add("aw-tenant-code", apiKey);
apiCall.ContentType = "application/json";
apiCall.ContentLength = noBody.Length; //noBody = empty string
Stream c = apiCall.GetRequestStream();
Encoding d = System.Text.Encoding.ASCII;
StreamWriter requestWriter = new StreamWriter(c, d);
requestWriter.Write(noBody);
requestWriter.Close();
WebResponse apiResponse = apiCall.GetResponse(); //This line will return an error.
This will also return the same error:
HttpWebResponse apiResponse = apiCall.GetResponse() as HttpWebResponse;
This will again return the same error:
string status;
using (HttpWebResponse response = apiCall.GetResponse() as HttpWebResponse)
{
status = response.StatusCode.ToString();
}
I just cant seem to correctly call the GetResponse Method.

Related

Is my method throwing me an exception because the proxy is dead?

So I've been getting into WebRequests recently and something that I found pretty interesting was making a connection through a proxy.
I looked at some blog posts for some code to get a general idea on how it worked and the most recent one would be this code snippet right here.
private static void requestProxy()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com");
WebProxy myproxy = new WebProxy("77.121.11.33", 1080);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string content = sr.ReadToEnd();
Debug.Print(content);
Console.WriteLine(content);
}
Console.ReadLine();
}
I tried making a request using that but it seems that it's throwing me an error everytime I try to use a proxy. However when I am not using a proxy it's not throwing me any errors, so I am assuming that the problem lays within the proxy. I tried using different ones but no go.
What I am doing wrong here and whats going on? How do I make a connection with a proxy properly?
Error message
System.Net.WebException: 'An error occurred while sending the request.
The server returned an invalid or unrecognized response'
https://imgur.com/ThxNWzb

Android issue with HttpWebRequest/HttpClient

I have asp.net web service. The web service has url like this:
mydomain dot com/service.asmx/getlocation?id=100
I always get below error. I tried both synchronous and async ways. I even tried to use Google.com but I always get below error:
Unhandled Exception:
System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
My code looks like this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Timeout = 60000;
request.Method = "GET";
// I get error here
using (WebResponse response = request.GetResponse())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
Thanks
Edit:
I tried it on different emulators- Nexus 7 Lollipop(5.1.0) and Nexus S(4.4.2)
It seems that returning JSON from a SOAP Service is quite tricky, I have looked at this stackoverflow question.

HTTPWebRequest GET request causing SSL connection issue

I am trying to connect to a RESTful API and when I access the URL from my browser I get an error stating I am missing headers which is what I was expecting to get. When I connect to the same URL using the below code I get an error stating "The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream". If I use the same code and change the URL to Google.com it works fine and to add to the mystery the connection I make to the API URL from my browser will generate an entry in the Apache logs on the API server, but the below code doesn't. Does anyone have any ideas why I would get that error?
var httpWebRequest = (HttpWebRequest)WebRequest.Create("HTTPS://URL.COM");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
string html = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Response.Write(responseString);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
UPDATE: I tried using HttpClient and got the same results:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://url.com/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("v1/person").Result;
if (response.IsSuccessStatusCode)
{
Response.Write(response);
}
else
{
Response.Write(response);
}
UPDATE 2: The below line of code seems to fix the problem. I am awaiting confirmation now. I am still a little baffled why this was required though.
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

http response code is OK when it should not be

I have a restful web service. If someone calls a particular method with the wrong key, I return this:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.Unauthorized;
response.StatusDescription = "Invalid key provided.";
If I call it using Firefox with Firebug running, send an invalid key and handle the error in my calling code like:
string serviceResponse = "";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string statusCode = response.StatusCode.ToString();
string statusDescription = response.StatusDescription.ToString();
}
}
catch(Exception ex)
{
serviceResponse = ex.Message;
}
the Response headers show:
HTTP:1.1 200 OK
Having handled the error, I can show a message on the screen. However, as soon as the 'using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)' line is hit, an error is thrown and the response object seems to be discarded.
If I don't put the HttpWebResponse code in a try catch block, a 401 unauthorized message shows in the browser but Firebug now shows:
HTTP:1.2 500 Internal Server Error
... which is weird, as I am sending a 401 back.
What is the point, in a Restful web service, of setting the response StatusCode and StatusDescription as, in a browser calling the web service, as soon as a 401 or 500 StatusCode is encountered, an error is thrown and the Response object discarded.
If a 500 or 401 is returned, how are you supposed to read the StatusDescription?

Handling The remote server returned an error: (500) Internal Server Error

I have a custom HTTP class I made for my application. It's just basic, the application is fairly simple. Anyway, sometimes the post method will return the following error:
Handling The remote server returned an error: (500) Internal Server Error.
My method is
public String post(String url, String postData)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = this.userAgent;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.CookieContainer = this.cookieJar;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
String source = reader.ReadToEnd();
return source;
}
I'm sending a request to update my Facebook status. Most of the time it works, the odd occasion it doesn't and throws an exception.
What's the best way to catch this exception so I can retry the request?
It may not be wise to repeat the request. There are instances where a request fails to return but the receiving server may have processed it, as a result, a retry would result in duplication.
It would be better if you raised an error response from this post method - By raising a specific exception - then it is the responsibility of the calling method on deciding what to do.
It may choose to repeat the request or ignore it or try to validate it was received before attempting to send again.

Categories