I have a foreach with an "If" and when the condition is true, I do a WebResponse to post my item in a server.
Sometimes the code run for two o more items but other times crashes with the following error:
The remote server returned an error: (407) Proxy Authentication Required.
The code:
WebClient client = new WebClient();
string authInfo = "admin:geoserver";
string address = "http://xxxxxxxx:8080/geoserver/rest/workspaces/";
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
WebRequest request = WebRequest.Create(address);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
byte[] bret = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>" + nameWS + "</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(bret, 0, bret.Length);
reqstr.Close();
try
{
WebResponse response = request.GetResponse();
response.Close();
}
My Environment is C# Visual Studio 2010
how often do you call this? as others have suggested it could be that the server is protected from DOS and your requests are seen like that. It's also valuable to dispose immediately all disposable objects with a using block for example. we had some issues once while leaving too many connections open to our web server, internally in our network. You could adjust your code to look like this:
using(var client = new WebClient())
{
string authInfo = "admin:geoserver";
string address = "http://xxxxxxxx:8080/geoserver/rest/workspaces/";
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
var request = WebRequest.Create(address);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
byte[] bret = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>" + nameWS + "</name></workspace>");
using (var reqstr = request.GetRequestStream())
{
reqstr.Write(bret, 0, bret.Length);
}
try
{
using (var response = request.GetResponse())
{
// your code here...
}
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine(exc.Message);
}
}
Related
I have some problems with code. I'm using HttpWebRequest class to do operations
Code as bellow:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768;
ServicePointManager.Expect100Continue = true;
//ServicePointManager.DefaultConnectionLimit = 5;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverName + authorizePath);
request.Abort();
byte[] bearerMatch = UTF8Encoding.UTF8.GetBytes("username:password");
//request.Proxy = null; //<TNI_20180808
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Timeout = 100;
//request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(bearerMatch);
string content = String.Format(authorizeBody, login, password);
content = "{" + content + "}";
try
{
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(content);
}
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseContent = reader.ReadToEnd();
token = responseContent.Replace('"', ' ').Trim();
}
//response.Close();
//request.Abort();
}
}
catch (Exception ex)
{
throw ex;
}
Until third operation everything is okey, unfortunately i don't know what to do. When application is trying to create request third time there is an timeout error:
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
I think that there is an opportunity to solve this with closing request and response in a proper way but i don't know how to do this. After increasing ServicePointManager.DefaultConnectionLimit operations were getting completed correctly.
Can you help me please? How should i abort or close request/response in a good way?
Thank you!
I have to add Host and User Agent to my request but there is no a function like "Host" or "User Agent"
without host I have unauthorized..
"WebException: The remote server returned an error: (401) Unauthorized."
my code:
var webRequest = WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
var whc = new WebHeaderCollection
{
"ACCESS_KEY: " + API_KEY,
"ACCESS_SIGNATURE: " + signature,
"ACCESS_NONCE: " + nonce
};
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
Screen of my code:
screen
With the lines "webRequest.Accept = "/";" etc. you actually set up values in the webRequest.Headers collection. Then with the line "webRequest.Headers = whc;" you basically overwrite the whole collection. You should add the custom headers like this:
var webRequest = WebRequest.Create("http://google.com") as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
webRequest.Headers.Add("ACCESS_KEY", API_KEY);
webRequest.Headers.Add("ACCESS_SIGNATURE", signature);
webRequest.Headers.Add("ACCESS_NONCE", nonce);
//...
}
When I debuged this, I saw all the necessary headers in the webRequest.Headers collection, but the host was missing. If I added it then got error stating I should set the header with "webRequest.Host" and not directly in the headers collection. I don't know if this is an error or it should work like this... Maybe this won't bother you at all.
I have a program that has a lot of HttpWebRequest calls in it. It deals a lot with external API requests to various streaming platforms (Twitch, Hitbox, Beam, YouTube). All of my requests seem to work fine.
Here is an example of one of my requests:
private void save_Click(object sender, RoutedEventArgs e)
{
string postUrl = "https://api.twitch.tv/kraken/channels/" + this.channelID;
string postData = "channel[status]=" + Uri.EscapeDataString(status.Text) +
"&channel[game]=" + Uri.EscapeDataString(game.Text);
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.Accept = "application/vnd.twitchtv.v5+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Headers.Add("Authorization", "OAuth " + password.Password);
request.Headers.Add("Client-ID", this.clientID);
request.Timeout = 15000;
try
{
Stream putStream = request.GetRequestStream();
putStream.Write(postByte, 0, postByte.Length);
putStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
MessageBox.Show("Unable to update channel information:\n" + err.Message);
}
}
However, there is an issue that if a request fails (such as a momentary internet hiccup), and the try-catch responds with an error due to a timeout, then no future HttpWebRequests will work until I restart my program.
This only happens if the error catch is initiated by a timeout.
Is there a reason why this happens and how can I fix it?
It's most likely being caused by resources that are not properly released causing locks.
Change your code to maybe call abort on HttpWebRequest on WebException and maybe also wrap the HttpWebResponse and putStream in a using statement.
private void save_Click(object sender, RoutedEventArgs e)
{
string postUrl = "https://api.twitch.tv/kraken/channels/" + this.channelID;
string postData = "channel[status]=" + Uri.EscapeDataString(status.Text) +
"&channel[game]=" + Uri.EscapeDataString(game.Text);
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.Accept = "application/vnd.twitchtv.v5+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Headers.Add("Authorization", "OAuth " + password.Password);
request.Headers.Add("Client-ID", this.clientID);
request.Timeout = 15000;
try
{
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(postByte, 0, postByte.Length);
using (var response = (HttpWebResponse) request.GetResponse())
{
//assign the response result to a variable else it's getting disposed
}
}
}
catch (WebException err)
{
request.Abort();
MessageBox.Show("Unable to update channel information:\n" + err.Message);
}
}
We've started using nancy in our open source project; https://github.com/CoiniumServ/coinium (a stratum/getwork/gbt pool server).
We basically need to support api calls over json-rpc. We're getting request similar to this;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Credentials = new NetworkCredential(User, Password);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
string jsonParam = (paramString != null) ? "\"" + paramString + "\"" : "";
string request = "{\"id\": 0, \"method\": \"" + method + "\", \"params\": [" + jsonParam + "]}";
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
dataStream.Write(byteArray, 0, byteArray.Length);
string reply = "";
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(str))
reply = reader.ReadToEnd();
return reply;
So basically the request is sent to / route with content-type application/json-rpc and we need to parse the inner provided request.
I've checked documentation but couldn't find my way out, does nancy support json-rpc?
Can anybody point me to right direction?
I've put a sample route as;
Post["/"] = #params =>
{
return "test";
};
but within the #params or Context couldn't find the actual json-rpc request string to parse.
Try either model binding (https://github.com/NancyFx/Nancy/wiki/Model-binding) or looking at Request.Body directly.
I am calling a REST web service which has given me this documentation
HTTP Method: POST
Path: /commit/{path}/add-node
Response Status 200, 302, 403, 404, 409, 503
Form Parameters
- name : attribute name
- message : commit message
Based on this documentation. I have written following C# code.
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
I also tried
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
var param = new { name = nodeName, message = commitMessage };
Stream reqStream = null;
string output = null;
try {
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
JsonConvert.SerializeObject(param)
);
request.ContentLength = buffer.Length;
reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
} catch (Exception ex) {
.....
}
Unfortunately in both cases, I get 415 Unsupported Media Type in both cases. What is wrong with my code?
The web Services is a REST based web service written in Java.
According to this forum post the ContentType property may not be supported from the Java web service. Are you sure it accepts application/json?