Android issue with HttpWebRequest/HttpClient - c#

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.

Related

read onedrive api errors

I am current using the following to try and create an upload session with the onedrive api
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + nODUserTokenObj.Access_Token;
request.ContentType = "application/json";
string data =
#"{
""#microsoft.graph.conflictBehavior"": ""replace""
}";
byte[] postBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postBytes.Length;
request.Accept = "application/json";
request.GetRequestStream().Write(postBytes, 0, postBytes.Length);
using (HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse())
{
using(StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
string theData = sr.ReadToEnd();
JObject test = JObject.Parse(theData);
}
}
Currently I am receiving an exception stating
The remote server returned an error: (409) Conflict.
However looking at the Microsoft documentation I should have a json object returned to me with more information.
What am I doing wrong that I am getting an exception thrown when it hits (HttpWebResponse)request.GetResponse() as opposed to receiving a json object with more error details?
I came across two solutions:
I initially resolved this by sending the request through Fiddler and reading the response there. This was fine for my situation as I was developing and just trying to figure out how the onedrive api functioned.
A solution going forward would be to follow something like this post suggests (How to get error information when HttpWebRequest.GetResponse() fails)
To summarize the post:
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
// Something more serious happened
// like for example you don't have network access
// we cannot talk about a server exception here as
// the server probably was never reached
}

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;

GetResponse() in API call causes (400) Bad Request error

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.

.NET service responds 500 internal error and "missing parameter" to HttpWebRequest POSTS but test form works fine

I am using a simple .NET service (asmx) that works fine when invoking via the test form (POST). When invoking via a HttpWebRequest object, I get a WebException "System.Net.WebException: The remote server returned an error: (500) Internal Server Error." Digging deeper, reading the WebException.Response.GetResponseStream() I get the message: "Missing parameter: serviceType." but I've clearly included this parameter.
I'm at a loss here, and its worse that I don't have access to debug the service itself.
Here is the code being used to make the request:
string postData = String.Format("serviceType={0}&SaleID={1}&Zip={2}", request.service, request.saleId, request.postalCode);
byte[] data = (new ASCIIEncoding()).GetBytes(postData);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Timeout = 60000;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = data.Length;
using (Stream newStream = httpWebRequest.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}
try
{
using (response = (HttpWebResponse)httpWebRequest.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("There was an error with the shipping freight service.");
string responseData;
using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("iso-8859-1")))
{
responseData = responseStream.ReadToEnd();
responseStream.Close();
}
if (string.IsNullOrEmpty(responseData))
throw new Exception("There was an error with the shipping freight service. Request went through but response is empty.");
XmlDocument providerResponse = new XmlDocument();
providerResponse.LoadXml(responseData);
return providerResponse;
}
}
catch (WebException webExp)
{
string exMessage = webExp.Message;
if (webExp.Response != null)
{
using (StreamReader responseReader = new StreamReader(webExp.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
}
}
throw new Exception(exMessage);
}
Anyone have an idea what could be happening?
Thanks.
UPDATE
Stepping through the debugger, I see the parameters are correct. I also see the parameters are correct in fiddler.
Examining fiddler, I get 2 requests each time this code executes. The first request is a post that sends the parameters. It gets a 301 response code with a "Document Moved Object Moved This document may be found here" message. The second request is a GET to the same URL with no body. It gets a 500 server error with "Missing parameter: serviceType." message.
It seems like you found your problem when you looked at the requests in Fiddler. Taking an excerpt from http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:
10.3.2 301 Moved Permanently
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible.
.....
Note: When automatically redirecting a POST request after
receiving a 301 status code, some existing HTTP/1.0 user agents
will erroneously change it into a GET request.
Here's a couple options that you can take:
Hard-code your program to use the new Url that you see in the 301 response in Fiddler
Adjust your code to retrieve the 301 response, parse out the new Url from the response, and build a new response with the new Url.
The latter option would be ideal if you're dealing with user-based input on the Url (like a web browser), since you don't know where the user is going to want your program to go.

Bad Request when sending request to WCF Service?

When I use the methods below to send an xml request to an asmx service, it works fine, the only difference is is that the content type is application/soap+xml. I am getting the error: 400 Bad Request. Here is the method I am using below to send the request via HTTP Post to the WCF Service:
private static void SendRequest(string request)
{
var req = (HttpWebRequest) WebRequest.Create("http://urltoservice.svc");
req.ContentType = "text/xml";
req.Method = "POST";
using (var stm = req.GetRequestStream())
{
using (var stmw = new StreamWriter(stm))
{
stmw.Write(request);
}
}
byte[] myData;
using (var webResponse = req.GetResponse())
{
var responseStream = webResponse.GetResponseStream();
myData = ReadFully(responseStream);
}
// Do whatever you need with the response
string responseString = Encoding.ASCII.GetString(myData);
}
It seems to throw it at the line: var webResponse = req.GetResponse()
What is the type of service that you are trying to call. Is it REST WCF service or SOAP WCF Service?
You can monitor your request using Fiddler to see how your request looks when it works and when it doesnt.
Also enable Tracing on your service to know why you get a 400 Bad Request.
No idea why this works, if someone can explain it it would be great. I needed to append the method name to URI in order for it to work, for example,
http://urltoservice.svc/MethodToCall

Categories