I have a wamp server on windows. SSL configured correctly. In browser it is working threw https: . I have a script test.php and I want to download and upload some POST data to it. I have my c# code:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
NameValueCollection values = new NameValueCollection();
values.Add("paramtest", "testval");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] result;
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);
string htmlCode = Encoding.UTF8.GetString(result);
textBox1.Text = htmlCode;
When runnign this code with http I got all the data. When put https, I got an error from the server:
400 Bad Request Bad Request
Your browser sent a request that this server could not
understand.
Have you got any idea how can I fix it?
Not sure whether this is the cause, but your url has a trailing '.' after the IP address:
try
result = client.UploadValues("https://127.0.0.1/test.php", "POST", values);
instead of
result = client.UploadValues("https://127.0.0.1./test.php", "POST", values);
Related
I have a cURL command provided by WooCommerce:
curl https://example.com/wp-json/wc/v2/orders \
-u consumer_key:consumer_secret
I'm using WebClient:
using (WebClient wc = new WebClient())
{
Uri url = new Uri("https://www.myhost.com/wp-json/wc/v2/orders");
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("consumer_key", keyValue);
byte[] responsebytes = wc.UploadValues(url, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
But I'm getting this error:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
What have I done wrong here? I'm pretty sure my url and key are correct.
EDIT: Have just tried this as suggested by CmdrTchort and David:
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}
Still receiving the same error.
EDIT: I have a suspicion I've been provided with invalid credentials I will update once this becomes clear...
I was given the wrong credentials. However that has not solved the issue.
I don't understand how consumer_key:consumer_secret is supposed to be represented in this request. There are two values: consumer_key and consumer_secret (I was only supplied with consumer_secret before, which I placed where keyValue is). I now assume that it is supposed to be of the form:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
where "consumer_key" and "consumer_secret" represent the unique values provided. This does not work. This is starting to get slightly irritating.
You're posting the consumer_key:consumer_secret as part of a form POST, but that's not what cURL was doing. That looks more like a GET request with supplied authentication. Perhaps something like this:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
and then making a GET request instead of a POST. With no values to upload, that part might be simplified. Maybe something like:
string responsebody = wc.DownloadString(url);
-u in curl passes the credentials as authorized headers and not as a dictionary of params.
You can add your credentials with :
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("username", "password");
Is your service responding and/or is it an untrusted or self-signed certificate?
If so , you can test ignoring the SSL-warning.
Btw, curl uses get by default (-X specifies method, which I can't see in your example) - so I'm assuming your only receiving by default and not actually posting values? If so you can use the DownloadString() directly.
So, if you're trying to get a file from this url you can do :
// IGNORE ALL SSL Certificates - would not do this in production
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate
{ return true; }
);
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}
I have a HTTPS URL which i am trying to connect to but not able to and keep getting 401 unauthorized.
I tried to access the same URL over Web Browser (both at home and in company) and was able to connect to it. After i execute the HTTPS URL (which has some parameters in it like date etc) in the browser, it prompts for username and pwd and when i enter it, it gives the xml back in response.
I tried following segment of code on my home PC and it worked fine but when i tried same in office network, it gave me 407 error. I thereafter embedded the proxy code in it and now i don't get 407 rather i keep getting 401. Please help
Working Code on Home:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Code within Organization with PROXY:
public static void WorkingCode()
{
string URL = "https://webservice.XYZ.com/display/?start_date=2015-05-06&end_date=2015-05-07";
Uri uri = new Uri(URL);
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("username123", "Password123");
string results;
/* PROXY CODE*/
WebProxy myProxy = new WebProxy("frproxyseczom.PPP.com", 8080);
myProxy.UseDefaultCredentials = true;
wc.Proxy = myProxy;
/*---------------*/
results = wc.DownloadString(uri);
Console.Write(results);
Console.Read();
}
Because of security reasons, i have modified some details such as URL's, username and pwd.
You're probably getting a 401 in the proxy code because you're missing "http://" in the web proxy address.
I would like to post some INFO and HEADER to destinationA, if it is verified, it will redirect to destinationA and ask user login. The code below successful to pass INFO and HEADER to opponent, but throw exception error during byte[] result = client.UploadValues(Url, "POST", values); , 408 request time out.
and how do i redirect user to the destinationA if this problem is solve? Please help me.. i have no idea how to work this out after i try to google for few days...MANY THANKS in advance..
NameValueCollection values = new NameValueCollection();
values.Add(PDATA, "");
string Url = "http://kh-api.mysabay.test/service/purchase/";
using (WebClient client = new WebClient())
{
client.Headers.Add("Authentication", "4");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] result = client.UploadValues(Url, "POST", values);
string ResultAuthTicket = Encoding.UTF8.GetString(result);
return ResultAuthTicket;
}
In my program I need to get the content of my site, however the return of DownloadString method of the webclient object returns null, however the most intriguing is that there is no exception. the status code is 200, the request is made perfectly, but the url returns an empty string.
WebClient wc = new WebClient();
String teste = wc.DownloadString("http://www.wiplay.com.br");
My site
http://www.wiplay.com.br
Seems like your website requires the user agent header to be set in order to respond.
Add the following before your call the DownloadString method:
wc.Headers.Add(HttpRequestHeader.UserAgent, "your useragent string");
In my case use of HttpClient and WebClient resulted in empty string despite status code 200 no matter what headers I set.
If somebody still suffers to this problem,using RestSharp like finally returned expected response body.
var dataString = JObject.FromObject(anonymousObject).ToString();
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddParameter("application/json", dataString, ParameterType.RequestBody);
var response = client.Post(request);
In the past I have successfully called a JSON webservice over HTTP
But, now I have to make a JSON POST over HTTPS.
I have tried using the code that works for HTTP and simply changed the url that is being called to https but it won't work.
This is the code i am using...
WebRequest wrGETURL;
wrGETURL = WebRequest.Create("https://apitest.example.com/geo/coverage/v1/?appId=2644571&appKey=836621d715b6ce4db5f007d8fa2214f");
wrGETURL.Method = "POST";
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string responseFromServer = objReader.ReadToEnd();
and the error message i am seeing in fiddler is:
fiddler.network.https> Failed to secure existing connection for apitest.example.com. A call to SSPI failed, see inner exception. InnerException: System.ComponentModel.Win32Exception (0x80004005): The client and server cannot communicate, because they do not possess a common algorithm
Can anyone help me with that I need to do to make a call over HTTPS please?
Do you need to authenticate or maybe a callback for the server certificate?
This works for me in most cases:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://someurl/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// Create NetworkCredential Object
NetworkCredential admin_auth = new NetworkCredential("username", "password");
// Set your HTTP credentials in your request header
httpWebRequest.Credentials = admin_auth;
// callback for handling server certificates
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"name\":\"TEST_123\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
I am using React and Expressjs and ran into this issue. Send your ie: https://www.google.com with out the https:
part of my router.js
router('/vod')
.rout.get('/vod', (req,res)=>{
res.send({message: "//www.google.com"});
App.js
function App() {
const [vod, setVod] = React.useState(null);
React.useEffect(() => {
fetch("/vod")
.then((res) => res.json())
.then((vod) => setVod(vod.message));
},
[]);
return (
<div className="App">
<header className="App-header">
<iframe src={"https:"+vod}
id="myIframe" autoPlay width={1000} height=
{500} frame></iframe>
</header>
</div>
);
in the iframe to change the source I used {"https:"+vod} to simulate the full url.
in your case try to combine your "result" like ("https:"+result)
I noticed that json grabs the : and messes the string up.