I'm calling Jenkins jobs from C# using the WebClient class and I'm not receiving any response even though the Jenkins job is triggering and executing properly. I need to read the headers to get the queue number and things like that, so I'm confused as to why this is happening. Below is my code, which works just fine except for "response" is always an empty string; not null, just an empty string:'
'
using (var wb = new WebClient())
{
string url = "http://url:8080/job/CloudTeam/job/Azure/job/Create-Azure-VM/buildWithParameters";
string queryString = "HOSTNAME=" + virtualMachine.Hostname + "&IPADDRESS=" + virtualMachine.IPAddress + "&RESOURCEGROUP=" + virtualMachine.ResourceGroup + "&STORAGEACCOUNT=" + virtualMachine.StorageAccount + "&BASEIMAGE=" + virtualMachine.BaseImage;
string password = "password";
string username = "user";
string basicAuthToken = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
wb.Headers["Authorization"] = "Basic " + basicAuthToken;
wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wb.Headers.Add("user", "user:password");
string response = wb.UploadString(url, queryString);
return response; <-- always an empty string
}
'
Related
I have read and read and played with this code inside out and I still cant work out how to get the refresh token. This in c#
I have tried different combo of access_type, prompt and approval_prompt params.
I keep revoking access by my user to the app, so when the auth code is being requested it does ask for myself to approve the app to be able to access.
I just want to get the refresh token so i can store it and keep refreshing.
here is the code below. I have removed the parts to get the auth code, but if it is needed i can add in. I wonder if anyone can simply spot something simply wrong.
string GetJsonFromAPICall(string p_url,string p_post_data, string p_b64_id_secret)
{
//string C_TOKEN_URL = "https://oauth2.googleapis.com/token";
string l_auth_string = "Basic " + p_b64_id_secret;
print("p_post_data = ", p_url + "?"+p_post_data);
print("Authorization", l_auth_string);
HttpWebRequest request = WebRequest.Create(p_url) as HttpWebRequest;
string postData = p_post_data;// "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
request.Headers.Add("Authorization", l_auth_string);
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
print("pos 20 in GetJsonFromAPICall");
print("length ", data.Length.ToString());
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
string getAccessToken(string p_b64_id_secret, string p_auth_code, string p_redirect_url)
{
//string l_url = "client_id="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_ID + "&client_secret="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_SECRET + "access_type=offline&prompt=consent&grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
string l_params = "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
l_params += "&access_type=offline";
l_params += "&prompt=consent";
l_params += "&approval_prompt=force";
//return GetJsonFromAPICall("https://oauth2.googleapis.com/token", l_params, p_b64_id_secret);
return GetJsonFromAPICall("https://www.googleapis.com/oauth2/v4/token", l_params, p_b64_id_secret);
}
var credentials = string.Format("{0}:{1}", C_GBQ_ONLINE_APP_APP_CLIENT_ID, C_GBQ_ONLINE_APP_APP_CLIENT_SECRET_ID);
var b64_id_secret = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
string l_auth_code = "xxxxx"; // worked out successfully earlier
l_json_returned = getAccessToken(p_b64_id_secret, l_auth_code, C_GBQ_ONLINE_APP_REDIRECT_URL);
the returned json is
l_json_returned = : {
"access_token": "FFFFFFFF",
"expires_in": 3569,
"scope": "https://www.googleapis.com/auth/cloud-platform.read-only https://www.googleapis.com/auth/bigquery",
"token_type": "Bearer"
}
I am working on a web application and it needs to track a location using an IP Address and I am new to sending requests to some APIs and getting a response from them. I was able to retrieve IP address of the user using Request.UserHostAddress
and was able to validate it using the following C# code
if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
{
string[] ips = ip.Split('.');
if (ips.Length == 4 || ips.Length == 6)
{
if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256
& System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
return true;
else
return false;
}
else
return false;
}
else
return false;
and I have got the API key and IP address required to request the following API
http://api.ipinfodb.com/v2/ip_query.php?key=[API KEY]&ip=[IP Address]&timezone=false
I know an HTTP GET REQUEST to the above would give me an XML response but not sure how to get started with the HTTP REQUEST in ASP.NET MVC using C#.
Can someone help me get started with this?
The response of IPInfoDB is a string like below:
OK;;74.125.45.100;US;United States;California;Mountain
View;94043;37.406;-122.079;-07:00
So we need to split into the various fields using C# codes below.
string key = "Your API key";
string ip = "IP address to check";
string url = "http://api.ipinfodb.com/v3/ip-city/?key=" + key + "&ip=" + ip;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
webReq.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
Stream answer = webResponse.GetResponseStream();
StreamReader response = new StreamReader(answer);
string raw = response.ReadToEnd();
char[] delimiter = new char[1];
delimiter[0] = ';';
string[] rawdata = raw.Split(delimiter);
ViewData["Response"] = "Country Code: " + rawdata[3] + " Country Name: " + rawdata[4] + " State: " + rawdata[5] + " City: " + rawdata[6];
response.Close();
Short Story:
I tried
Encoding.ASCII.GetBytes("mystring")
but it seems not to be working...
Long Story:
I am trying to call an API and I have this python sample code available:
userpass = username + ":" + password
encoded_credentials = b"Basic " + base64.b64encode(userpass.encode('ascii'))
headers = {'Version': '2.0', 'Accept': 'application/json', 'Authorization': encoded_credentials}
url = 'https://' + server_ip + '/api/help/capabilities'
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
The c# code I made is:
string userpass = username + ":" + password;
byte[] encodedbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(userpass);
var encoded_credentials = Encoding.ASCII.GetBytes("Basic ") + Convert.ToBase64String(encodedbytes);
var request = (HttpWebRequest)WebRequest.Create("https://" + server_ip + "/api/help/capabilities");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Authorization", encoded_credentials);
var response = (HttpWebResponse)request.GetResponse()
And the result I get is 401, unauthorized... so I believe I miss something in the encoding procedure of the username-password!
var encoded_credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userpass));
That is the answer to my "Long Story" question!
I managed to figure out after debugging the python code (that did authorize), so I took the encoded_credentials and used it in my c# code, so it successfully authorized too...
Then I compared the faulty value to the correct and with a couple of tries, I ended up with the correct one!
This leads me to the conclusion that the correct answer to the "Short Story" question is just:
"mystring"
Im trying to convert Java program to C#. This programe sent JSON object to server using a HTTP POST. Java program works fine. return 200. But C# program return 400 (bad request). What can be the cause
Java Code
String base_url = "https://test-url.com";
String username = "test-user";
String password = "test-pass";
String client_id = "test-client";
String client_secret = "test-key";
String loginUrl = base_url + "session/login";
Charset utf8 = Charset.forName("UTF-8");
ContentType jason_content_type = ContentType.create("application/json", utf8);
try {
HttpClient c = HttpClients.custom().setUserAgent(client_id + "/1.0").build();
HttpPost p = new HttpPost(loginUrl);
String json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
p.setEntity(new StringEntity(json_str, jason_content_type));
HttpResponse r = c.execute(p);
int status = r.getStatusLine().getStatusCode();
} catch (IOException e) {
System.out.println(e);
}
C# Code
string base_url = "https://test-url.com";
string username = "test-user";
string password = "test-pass";
string client_id = "test-client";
string client_secret = "test-key";
string login_url = base_url + "session/login";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(login_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.UserAgent = client_id + "/1.0";
httpWebRequest.ProtocolVersion=HttpVersion.Version11;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
{
string json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
streamWriter.Write(json_str);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Try out adding in C# :
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
I am trying to get user token and build the URL so that user need not login everytime they click the file. below is my code.
My question is do I need to pass whole of the token value shown below or??
The token value I am getting is
symmetric:algorithm:QUVT:keyid:NTZkYTNkNmI=:data:7P9aJHzkfGTOlwtotuWGaMqfU9COECscA9yxMdK64ZLa298A3tsGlHKHDFp0cH+gn/SiMrwKfbWNZybPXaltgo5e4H4Ak8KUiCRKWfS68qhmjfw69qPv9ib96vL3TzNORYFpp/hrwvp8aX4CQIZlBA==
The problem is, once i copy the URL and past it in the browser, it is taking me to the login page. Though I am not getting any errors, it should take users directly to the imageviewer but instead it takes me to login page, if I login it is opening the file correctly.
What am I doing wrong?
string text = "";
string userName = "userName";
string pwd = "*****";
fileNetID = "{5FCE7E04-3D74-4A93-AA53-26C12A2FD4FC}";
Uri uri = null;
string workplaceURL = "http://filenet:9081/WorkPlaceXT";
uri = new Uri(workplaceURL + "/setCredentials?op=getUserToken&userId=" + this.encodeLabel(userName) + "&password=" + this.encodeLabel(pwd) + "&verify=true");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(uri);
System.Net.WebResponse webResponse = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
String token = streamReader.ReadToEnd();
string contentURL = string.Empty;
contentURL = workplaceURL + "/getContent?objectType=document&impersonate=true&objectStoreName=OBJECTSTORE&id=" + HttpUtility.UrlEncode(fileNetID);
contentURL += "&ut=" + HttpUtility.UrlEncode(encodeLabel(token));
return contentURL;
Here is my function, you can see the last couple lines how I unroll the token at the end:
public static string getCEUserToken(string baseURL, string uid, string pwd)
{
string UserToken = "";
System.Net.WebRequest request = System.Net.WebRequest.Create(baseURL + "/setCredentials?op=getUserToken&userId=" + uid + "&password=" + pwd +
"&verify=true");
request.Method = "POST";
System.Net.WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
byte[] token = new byte[response.ContentLength];
stream.Read(token, 0, (int)response.ContentLength);
response.Close();
foreach (byte chr in token)
UserToken += System.Convert.ToChar(chr);
return System.Web.HttpUtility.UrlEncode(UserToken);
}