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;
Related
I have swagger URL http://somehost/swagger/index.html
end methods there as shown on image:
As someone said to me http://somehost/api/Referral/GetReferralByNumber is API address which I can refer it by HTTP request.
static void Main(string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
string result = client.DownloadString("http://somehost/api/Referral/GetReferralByNumber");
}
catch (System.Net.WebException ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
this is code for testing API, but
System.Net.WebException: The remote server returned an error: (404)
Not Found exception
is thrown. any help?
Client.DownloadString() makes an GET request. Your action supports POST. Try to use HttpClient, it should be better for your case.
You are hitting a Get Request and for Get request there is no such endpoint.
You should try adding the HTTP option Post to the server.
Code:
private static readonly HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/referral/GetReferralByNumber", data);
Where data is the data which should be posted to the server.
You should create an http client and use POST like this:
var method = HttpMethod.Post;
var endPoint = "http://somehost/api/Referral/GetReferralByNumber";
var request = new HttpRequestMessage(method, endPoint);
var client = new HttpClient();
var response = await httpClient.SendAsync(request);
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
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.
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.
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.