401 error when try to connect to Lighthouse API - c#

I'm trying to connect to the Lighthouse api using C# code. This is the php example https://support.lighthouserocks.com/hc/en-gb/articles/201319732-API-The-Basics which it describe how to do this. But I'm fails with it. I was try both NetworkCredentials & send in the Header but still have 401 Unauthorized access to it, here is the code:
public string RequestResponse()
{
HttpWebRequest webRequest = WebRequest.Create(HomeUrl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
string auth = CreateAuthorization("domain.lhlive.com", "user", "token");
webRequest.Headers["auth"] = "Basic " + auth;
//webRequest.Credentials = new NetworkCredential("user", "token");
//webRequest.PreAuthenticate = true;
//webRequest.Headers.Add("auth", "user, token");
webRequest.Accept = "application/vnd.lighthouse.v1.hal+json";
Stream responseStream = null;
StreamReader responseReader = null;
string responseData = "";
try
{
WebResponse webResponse = webRequest.GetResponse();
responseStream = webResponse.GetResponseStream();
responseReader = new StreamReader(responseStream);
responseData = responseReader.ReadToEnd();
}
finally
{
if (responseStream != null)
{
responseStream.Close();
responseReader.Close();
}
}
return responseData;
}
public void Test()
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
client.Headers["ContentType"] = "application/json";
client.Headers["Accept"] = "application/vnd.lighthouse.v1.hal+json";
//client.Headers["Lighthouse Username"] = "user";
//client.Headers["API Key"] = "token";
client.Headers["WWW-Authenticate"] = "user, token";
byte[] arr = client.DownloadData("https://domain.lhlive.com/contacts");
Console.WriteLine("--- WebClient result ---");
Console.WriteLine(arr.Length);
}
}
anybody know what I should to do?

Hard to say because I can't access Lighthouse but try the following (notice how auth header is set).
var webRequest = WebRequest.Create("http://some.endpoint.com/") as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Accept = "application/vnd.lighthouse.v1.hal+json";
webRequest.ContentType = "application/json";
webRequest.Headers["Authorization"] = string.Format("Basic {0}",
Convert.ToBase64String(Encoding.Default.GetBytes(
string.Format("{0}:{1}", "your username", "your API key"))));
var response = webRequest.GetResponse();
var stream = response.GetResponseStream();
var data = (new StreamReader(stream)).ReadToEnd();
In this case your Authorization header looks like "Basic eW91ciB1c2VybmFtZTp5b3VyIEFQSSBrZXk=".

Related

C# HttpWebRequest Form post data

In my C# Winform application I'm trying to send form post data to a web page of Instagram:
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.instagram.com/create/configure/");
req.Method = "POST";
if (req.CookieContainer == null)
req.CookieContainer = new CookieContainer();
foreach (System.Net.Cookie cookie in cookies)
{
req.CookieContainer.Add(cookie);
}
String postData = "upload_id=" + upload_id + "&caption=Wow&usertags=&custom_accessibility_caption=&retry_timeout=";
var data = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Accept = "*/*";
req.Referer = "https://www.instagram.com/create/details/";
req.Headers["accept-encoding"] = "gzip, deflate, br";
req.Headers["accept-language"] = "en-US,en;q=0.9";
req.Headers["origin"] = "https://www.instagram.com";
req.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1";
req.Headers["x-requested-with"] = "XMLHttpRequest";
req.Headers["x-ig-app-id"] = "1217981644879628";
req.Headers["x-csrftoken"] = csrftoken;
req.Headers["x-instagram-ajax"] = rolloutHash;
using (Stream requestStream = req.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
return source;
}
catch (Exception e)
{
int t = 0;
t++;
}
return "";
But I'm always getting 400 Exception from it. Any idea what can be the problem?
You are probably using an old version of api documentation, currently instagram api allows very limited actions.
check this
https://www.instagram.com/developer/endpoints/
and this
https://developers.facebook.com/docs/instagram-api/reference/media

Cannot login in web app via C#

I'm trying to log in at http://carkit.kg (django app) via C# with following code
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
tokenRequest.CookieContainer = new CookieContainer();
string token = "";
using (var response = (HttpWebResponse)tokenRequest.GetResponse()) {
token = response.Cookies["csrftoken"].ToString().Split('=')[1];
}
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
var cache = new CredentialCache();
cache.Add(new Uri("http://carkit.kg"), "Basic", new NetworkCredential(username, password));
loginRequest.Credentials = cache;
loginRequest.PreAuthenticate = true;
loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token) {Domain="carkit.kg"});
Debug.Log(token);
byte[] data = Encoding.ASCII.GetBytes("username=" + username + "&password=" + password + "&csrfmiddlewaretoken=" + token);
loginRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
loginRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
loginRequest.Headers.Add("Cache-Control", "max-age=0");
loginRequest.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
//loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.Headers.Add("Origin", "http://carkit.kg");
loginRequest.Referer = "http://carkit.kg/";
loginRequest.Headers.Add("UpgradeInsecureRequests", "1");
loginRequest.Headers.Add("XCompress", "null");
loginRequest.Headers.Add("ContentType", "application/x-www-form-urlencoded");
loginRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
loginRequest.Headers.Add("X-CSRFToken",token);
loginRequest.ContentLength = data.Length;
loginRequest.Timeout = 3000;
loginRequest.GetRequestStream().Write(data, 0, data.Length);
loginRequest.Headers.Add("X-CSRFToken", token);
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);
Both requests running well, but last line returns incorrect uri (if login is correct it should redirect me to /game and stay at / in other case) - anyway it returns /. Redirect is enabled and you see which headers I've included into request. What is the problem?
I've just used django-rest-framework as authentication service and LogIn method got this representation:
public void LogIn(string username, string password)
{
var request = (HttpWebRequest)WebRequest.Create("http://carkit.kg/api/v1/auth/login/");
var postData = "username=" + username;
postData += "&password=" + password;
var data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try {
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
// Successful login
}
else {
serverMessenger.SendErrorMessage(0);
Debug.LogError("Cannot Find User. TryToLogin finished");
}
} catch (WebException e) {
serverMessenger.SendErrorMessage(0);
Debug.LogError("Cannot Find User. TryToLogin finished");
}
}

How to handle status 302 redirect in c# httpwebreqest ASP.NET

Here is my code:
#{
//string postString = "parameter=value";
const string contentType = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.Expect100Continue = false;
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = WebRequest.Create("http://somehost:8080/myApp") as HttpWebRequest;
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = false;
webRequest.ContentType = contentType;
webRequest.CookieContainer = cookies;
webRequest.ContentLength = postString.Length;
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse;
string location = resp.Headers["Location"];
Response.Redirect(location);
}
response from http://somehost:8080/myApp is 302 redirect to some other domain. If I use webRequest.AllowAutoRedirect = true; and write response (Response.Write(StreamReader(resp.GetResponseStream()).ReadToEnd())), resulting html is not shown correctly because resources with relative links could not be resolved.
So, I came up with this solution but I feel that it's not correct. It seems to me that my solution is sort of 'hackaround'.
Is there better solution?
change your relative url into absolute
url = objHttpWebResponse.Headers["Location"].ToString();
MessageBox.Show("Redirect To " + objHttpWebResponse.Headers["Location"]);
System.Threading.Thread.Sleep(2000);
Uri final = new Uri(new Uri(txtURL.Text), url);
string finalurl = final.AbsoluteUri;
download(finalurl);

missing post data by using HttpWebRequest

I got a problem on posting data by using HttpWebRequest.
There is a string(ie. key1=value1&key2=value2&key3=value3) and I have post it to a site (ie. www.*.com/edit), but ,I don't know why that sometimes it's nothing wrong , but sometimes ,the first key=value1 will be missing, only key2=value&key3=value3 that can find in HttpAnalyzer.
public static string SubmitData(string Url, string FormData, CookieContainer _Cc, string ContentType)
{
Stream RequestStream = null, ResponseStream = null; StreamReader Sr = null;
HttpWebRequest HRequest = (HttpWebRequest)WebRequest.Create(Url);
try
{
HRequest.CookieContainer = _Cc;
HRequest.Method = "POST";
HRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)";
HRequest.ContentType = ContentType;
HRequest.ContentLength = FormData.Length;
//byte[] BFromData = new ASCIIEncoding().GetBytes(FormData);
byte[] BFromData = Encoding.ASCII.GetBytes(FormData);
BFromData = Encoding.Convert(Encoding.ASCII, Encoding.UTF8, BFromData);//ascii → utf8
RequestStream = HRequest.GetRequestStream();
RequestStream.Write(BFromData, 0, BFromData.Length);
//RequestStream.Write(utf8Bytes,0,utf8Bytes.Length );
HttpWebResponse HResponse = (HttpWebResponse)HRequest.GetResponse();
ResponseStream = HResponse.GetResponseStream();
Sr = new StreamReader(ResponseStream, Encoding.UTF8);
return Sr.ReadToEnd();
}
catch
{
return "";
}
finally
{
if (null != RequestStream) RequestStream.Close();
if (null != ResponseStream) ResponseStream.Close();
if (null != Sr) Sr.Close();
}
}
Use Fiddler to see how the request looks like when you click on the form then try using this approach and modify what you need for your request.
public static void PostDataAndDoSomething()
{
string URI = "http://www.something.com";
//make your request payload
string requestBody = String.Format("{{'param1': {0}, 'param2': {1}}}",value1, value2); //json format
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI); //make request
// set request headers as you need
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json, text/javascript;
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody); //write your request payload
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();
//do something with your data, deserialize, Regex etc....
}

C# httpwebrequest get 401 Unauthorized

try
{
HttpWebRequest request = (Http WebRequest)WebRequest.Create("http://yigg.de/login");
request.Method = "GET";
request.Timeout = 10000;
request.ReadWriteTimeout = 30000;
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers["Accept-Language"] = "en-us,en;q=0.5";
request.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) (Prevx 3.0.5)";
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://yigg.de/login"), "Basic", new NetworkCredential("user", "pass"));
request.Credentials = cc;
request.CookieContainer = container;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string htmldoc = reader.ReadToEnd();
response.Close();
return htmldoc;
}
catch (Exception ex)
{
return ex.Message;
}
I used above code and i always get "The remote server returned an error: (401) Unauthorized". Please help me. Thanks!

Categories

Resources