I am using the following function to receive an Artifacory repo mapping:
private string LoadHttpPageWithBasicAuthentication(string url, string username, string password)
{
Uri myUri = new Uri(url);
WebRequest myWebRequest = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;
NetworkCredential myNetworkCredential = new NetworkCredential(username, password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream responseStream = myWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
responseStream.Close();
myWebResponse.Close();
return pageContent;
}
The URL that i am trying to pass looks like that -
http://ArtifactoryRepo?list&deep=1&listFolders=1&mdTimestamps=1
But from the result it seems that the request ignores part of the URL.
The results that received are only for that part of the URL -
http://ArtifactoryRepo
I tried to split URL for two separate parameters but it doesn't worked
Any ideas ?
Thnaks
First there was a problem with credentials, so i used Convert.Tobase64string() function.
And webReq.Method was not defined.
Finally found that function to do the job.
Related
I have been trying to get an API response from a url that requires a basic authorization including username and password along with clientid in the header as I am getting response from API if I call it in Postman. I want to try the same thing in my asp.net c# project. But always get error 400 Bad request.
Here is my code;
NetworkCredential networkCredential = new NetworkCredential(UserName, Password);
CredentialCache myCredentialCache = new CredentialCache { { new Uri(url4), "Basic", networkCredential } };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url4);
UTF8Encoding encoding = new UTF8Encoding();
request.Method = WebRequestMethods.Http.Get;
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
using (WebResponse response = request.GetResponse()) //This is where I get error Bad request
{
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
// StreamReader sr = new StreamReader(stream);
string strResult = reader.ReadToEnd();
for (int i = 0; i < strResult.Length; i++)
{
if (strResult.Contains(getValue) == true)
{
Label1.Text = strResult;
}
else
{
//error
}
}
reader.Close();
}
}
}
Can anyone help me?
Plaese check it :
Uri requestUri = null;
Uri.TryCreate((linkUrl), UriKind.Absolute, out requestUri);
NetworkCredential nc = new NetworkCredential(username, password);
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc);
cache.Add(new Uri(linkUrl), "NTLM", new NetworkCredential("", ""));
// Requesting query string
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Credentials = cache;
// Getting response from WebRequest
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream());
I have tried every variation of the below I can think of.
client.Credentials = new NetworkCredential(ftpInfo.ftpUserName, ftpInfo.ftpPassWord);
client.BaseAddress = "ftp://99.999.9.99";
var response = client.UploadFile("testFile.txt", "C:\\ftproot\\testfile\\012\\Drop\\testFile.txt");
I know the username and password are correct.
If I connect to the server using filezilla from the same box it works.
I have tried not haivng ftp:// on it -- I have to be missing something very simple.
Here is the error:
{"Unable to connect to the remote server"}
Response {System.Net.FtpWebResponse} System.Net.WebResponse {System.Net.FtpWebResponse}
ContentType '($exception).Response.ContentType' threw an exception of type 'System.NotImplementedException' string {System.NotImplementedException}
UPDATE:
I don't know what is wrong with the question. I have given as much info as I have on it.
Here is a current test using some of the suggestions in the notes.
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("password", "loginname");
client.UploadFile("ftp://99.999.6.130/testFile.txt", "STOR", "c:\\testfile.txt");
}
That just states that I am not logged in.
The below is working....I will close the question out when it lets me.
Finale Update -- working solution:
public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, password);
// Copy the entire contents of the file to the request stream.
var sourceStream = new StreamReader(file);
var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
var getResponse = request.GetResponse();
Console.WriteLine($"{fileContents.Length} {getResponse} ");
}
}
The below is a working solution.
public static bool UploadFile(string url, string userName, string password, string file, out string statusDescription)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, password);
// Copy the entire contents of the file to the request stream.
var sourceStream = new StreamReader(file);
var fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
var getResponse = request.GetResponse();
Console.WriteLine($"{fileContents.Length} {getResponse} ");
}
}
I'm trying to scrape a website that requires a login. Getting an error that I haven't received before, copied the code from another forum successfully in the past:
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
with the code:
Stream newStream = http.GetRequestStream(); //open connection
Here's the entire code:
#{
var strUserId = "userName";
var strPassword = "password";
var url = "formSubmitLandingSite";
var url2 = "pageToScrape";
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData = "email=" + strUserId + "&password=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
Stream newStream = http.GetRequestStream(); //open connection
newStream.Write(dataBytes, 0, dataBytes.Length); // Send the data.
newStream.Close();
string sourceCode;
HttpWebResponse getResponse = (HttpWebResponse)http.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
sourceCode = sr.ReadToEnd();
}
Response.Write(sourceCode);
}
You're creating a new request object here:
http = WebRequest.Create(url2) as HttpWebRequest;
Keep in mind that the default HTTP verb used is GET. Then you try to open the request stream here:
Stream newStream = http.GetRequestStream();
This method is used to enable writing data to the request's content. However, GET requests don't have content. As you do in the code above the error, you'll need to use a different HTTP verb. POST is most common for this, and is what you're using above:
http.Method = "POST";
So just use a POST request again. (Assuming, of course, that's what the server is expecting. In any event, if the server is expecting content then it's definitely not expecting a GET request.)
I have read several posts about login in to sites that needs email and password, but i couldn't find a solution about logging in to a specific site called geni.com. Is there a way?
CookieContainer cookie;
string user = "somemail#somehost.com";
string pass = "123456";
string formUrl = "http://www.geni.com/login/";
string formParams = String.Format("profile_username={0}&password={1}", "MYUSERNAME", "MYPASS");
string cookieHeader;
HttpWebRequest myWebRequest;
WebResponse myWebResponse;
String URL = textBox1.Text;
myWebRequest = (HttpWebRequest)WebRequest.Create("formUrl");
myWebRequest.ContentType = "application/x-www-form-urlencoded";
myWebRequest.Method = "POST";
string login = string.Format("go=&Fuser={0}&Fpass={1}", user, pass);
byte[] postbuf = Encoding.ASCII.GetBytes(login);
myWebResponse = myWebRequest.GetResponse(); //Returns a response from an Internet resource
cookieHeader = myWebResponse.Headers["Set-cookie"];
cookie = myWebRequest.CookieContainer = new CookieContainer();
myWebRequest.CookieContainer = cookie;
Stream streamResponse = myWebResponse.GetResponseStream();
StreamReader sreader = new StreamReader(streamResponse);
Rstring = sreader.ReadToEnd();
I am a bit confused, can anybody help me??
Here's a link to their API documentation. To login you'll want to call their API like this:
https://www.geni.com/platform/oauth/request_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
I got this from Load web browser with web response. and am wondering how I can use this code to use proxies that need a username and password to be able to work.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://example.com");
webRequest.Proxy = new WebProxy(host, port);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentStream = receiveStream;
var webProxy = new WebProxy(host,port);
webProxy.Credentials = new NetworkCredential("username", "password", "domain");
var webRequest = (HttpWebRequest)WebRequest.Create("http://example.com");
webRequest.Proxy = webProxy;