HTTP Post Authentication error - c#

Here is my code
string URL = "https://api.fastspring.com/accounts";
using (var wb = new WebClient())
{
var data = new NameValueCollection();
var contact = new NameValueCollection();
data["contact"] = "first="+FirstName+"&last="+LastName+"&email="+Email+"&company="+Company;
data["language"] = Language;
data["country"] = Country;
var headers = new WebHeaderCollection();
headers["Authorization"] = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password"));
headers["User-Agent"] = "request";
//headers["Content-Type"] = "application/json";
wb.Headers = headers;
var response = wb.UploadValues(URL, "POST", data);
return (System.Text.Encoding.UTF8.GetString(response)).Split('"')[3];
}
My problem is that i keep on getting a 401 error saying unauthorised. For one, is my authentication syntax correct? also is my entire setup for sending an HTTP request to the server correct?
here are some useful resources about the fastspring api if it would help:
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api/accounts#id-/accounts-Createanaccount
http://docs.fastspring.com/integrating-with-fastspring/fastspring-api

Related

write a http post request to bot framework running on localhost

I have a bot running on http://localhost:3978/api/messages.
Instead of debugging it using an emulator, can I go about using a http post request to the messaging endpoint of the bot?
If so, how do I go about doing it?
I am using c# microsoft bot framework, and I am new to this application.
I do not want to use any channels or DirectLine api, just using Httpclient.
You can do this with C# using code similar to below. Note that you would have to construct an Activity to send by setting the appropriate properties for your needs, which is not included in this code.
//make a call to get an auth token
string token;
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["grant_type"] = "client_credentials";
values["client_id"] = "YOUR APP ID";
values["client_secret"] = "NcOXRwb51joibEfzUuNE04u";
values["scope"] = "YOUR APP ID/.default";
var response =
client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);
var responseString = Encoding.Default.GetString(response);
var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
token = result.access_token;
}
//you will need to adjust this value for your project.
//this example for a proxy project so the service url here is
//just an arbitrary endpoint I was using to send activities to
activity.ServiceUrl = "http://localhost:4643/api/return";
var jsonActivityAltered = JsonConvert.SerializeObject(activity);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", $"Bearer {token}");
try
{
var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Have you tried using something like postman? (it's free and easy to use)
https://www.getpostman.com/
You can also write scripts in postman
otherwise you can just go to the endpoint of your API in the browser
http://localhost:3978/api/
I see you mentioned you wanted to make a console application.
You could do that. I'd suggest using postman though.
Here is an example of sending a file as well as some querystring data and Authentication using a Bearer token.
Sorry it may not be exact. Had to do a bit of copy pasting/deleting from some code examples if have
using (HttpClient client = new HttpClient())
{
JObject jsonModel = new JObject();
client.BaseAddress = new Uri("http://localhost:3978/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("firstname", lastname),
new KeyValuePair<string, string>("lastname", lastname),
new KeyValuePair<string, string>("payloadFile", FileName)
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
ByteArrayContent fileContent = new ByteArrayContent(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
string FullxmlString = File.ReadAllText(Path.Combine(HttpContext.Current.Server.MapPath("~/uploads/output/" + FileName)));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("payloadFile") { FileName = "payloadFile" };
multipartFormDataContent.Add(fileContent);
HttpResponseMessage response = client.PostAsync("api/message", multipartFormDataContent).Result;
string returnString = response.Content.ToString();
using (HttpContent content = response.Content)
{
string res = "";
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
}
}

Jira Rest API login error in JIRA SERVER using C#

I want connect to jira server using C# Rest api
https://jira.myserver.co.kr/rest/auth/1/session
enter code here
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
... more
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
the remote server returned an error (404)
I tried different work arounds but all went in vain. May I know why this error is coming? What could be the resolution of this error?
You can search for a reason of this error in different ways:
by looking at logs of JIRA server, there might be some messages/stacktraces there (for example, atlasian-jira.log);
by using some tool to perform/debug/test REST calls (for example, postman), and when it's start working in tool you can write code to do it programmatically. JIRA can return description of error in the response, and tool can show it to you.
When you get this information it can give you exact reason why it is not working. Once I got 403 error and it was because threshold of unsuccessful login attempts was exceeded, I logged into JIRA server using web browser (and entered captcha), and after that I was able to obtain session through application code.
I can successfully obtain session from JIRA in the following way using postman:
Request type: POST
URL: https://myjiraserver.com/rest/auth/1/session
Body: {"username":"myusername","password":"mypassword"}
Headers: Content-Type:application/json
you can do something like this:
namespace YOUR_NAME_SPACE
{
public class jira
{
public static string createTicket(string url, string data)
{
try
{
var client = new System.Net.Http.HttpClient();
string base64Credentials = GetEncodedCredentials();
var header = new AuthenticationHeaderValue("Basic", base64Credentials);
client.DefaultRequestHeaders.Authorization = header;
var content = new StringContent(data, Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
var response = result.Content.ReadAsStringAsync().Result;
// You can call putIssue if you want
return response;
}
catch (System.Net.WebException ex)
{
Console.WriteLine("Exception Occurred" + " : {0}", ex.Message);
throw;
}
}
private static string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", "LOGIN", "PASSWD");
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
public static string jiraSerialise(string project, string summary, string description, string issutype, string author)
{
JObject valuesToJson =
new JObject(
new JProperty("fields",
new JObject(
new JProperty("project",
new JObject(new JProperty("key", project))),
new JProperty("summary", summary),
new JProperty("description", description),
new JProperty("issuetype",
new JObject(new JProperty("name", issutype))),
new JProperty("assignee",
new JObject(new JProperty("name", author))))));
return valuesToJson.ToString();
}
public static string putSerialize(string key, string value)
{
JObject valueToJson =
new JObject(
new JProperty(key, value));
return valueToJson.ToString();
}
public static string putIssue(string response, string author, System.Net.Http.HttpClient client)
{
JObject jsonResponse = JObject.Parse(response);
Dictionary<string, string> dictResponse = jsonResponse.ToObject<Dictionary<string, string>>();
string issueUrl = dictResponse.Last().Value;
string issueAssignee = issueUrl + "/assignee";
var authorContent = new StringContent(author, Encoding.UTF8, "application/json");
var authorResult = client.PutAsync(issueAssignee, authorContent).Result;
var authorResponse = authorResult.Content.ReadAsStringAsync().Result;
Console.WriteLine(authorResponse);
return authorResponse;
}
}
}
And now you can call this class like that:
string data = jira.jiraSerialise("lala", "nameVulnerabilty", "descriptionField", "Bug", "author");
string url = "http://YOUR_URL/rest/api/2/issue/";
Console.WriteLine(jira.createTicket(url, data));
Hope it helps :)

How to post json string on some specific url

I want to log amplitude on https://api.amplitude.com/httpapi using the following code:
private void LogAmplitude()
{
using (var client = new WebClient())
{
var url = "https://api.amplitude.com/httpapi";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var model = new { user_Id = "userId", event_type = "Event" };
var jss = new JavaScriptSerializer();
var data = jss.Serialize(model);
string parameters = "api_key=" + "apiKey" + "&event=" + data;
var response = client.UploadString(url, parameters);
}
}
But when I run this method it gives me 400(bad request) error. I have tried posting the data using postman through following url:
https://api.amplitude.com/httpapi?api_key=apiKey&event={"user_id":"userId","event_type":"test"}
This works totally fine but when I try to post data using the above method it always gives me error. I am not sure what I am doing wrong because I am doing this kind of work for the very first time. So can anybody help?
In the documentation says that you can use GETwith urlencoded parameters.
Try this:
using (var client = new WebClient())
{
var url = "https://api.amplitude.com/httpapi";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var model = new { user_id = "userId", event_type = "Event" };
var jss = new JavaScriptSerializer();
var data = jss.Serialize(model);
string parameters = "api_key=" + "apiKey" + "&event=" + System.Uri.EscapeDataString(data);
var response = client.DownloadString ($"{url}?{parameters}");
}

HTTP POST is giving unauthorized 401 Exception

When calling the same method on google chrome postman after logging in, i'm getting the json object as shown below.
but when i try to get the same json result in codebehind (C#). I'm getting Unauthorized 401 exception.
I'm using my code like this.
using (var clientSideTab = new WebClient())
{
var valSideTab = new System.Collections.Specialized.NameValueCollection { { "username", UserID }, { "Password", strPassword } };
string UpldDataSideTab = "https://resapistage.namechanged.com/v3/secure/Login.aspx?userId=" + UserID + "&passwd=" + strPassword + " ";
SystemComponentWrapper SPPostWrapper = new SystemComponentWrapper();
SystemComponentData request = new SystemComponentData();
SystemComponentaddressId addressId = new SystemComponentaddressId();
addressId.type = "AddressId";
addressId.id = 19863;
addressId.serial = "";
request.addressId = addressId;
request.compId = null;
request.getCompParams = true;
request.filterForAddress = false;
SPPostWrapper.request = request;
var postJson = JsonConvert.SerializeObject(SPPostWrapper);
Encoding encoding = new UTF8Encoding();
string postData = postJson.ToString();
byte[] bdata = encoding.GetBytes(postData);
string URI = "https://resapistage.namechanged.com/v3/api/secure/json/AddressInfo.svc/getSystemComponentsV2";
clientSideTab.UploadValues(UpldDataSideTab, "POST", valSideTab);
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.UploadString(URI,"POST", postData);
//clientSideTab.UploadData(URI, "POST", bdata);
String jsonresponse = "failed";
Label1.Text = jsonresponse;
}
I'm getting this error everytime. please help me.
use like this.
string cookie = strCookie[0]; // fetch your cookie after logging in
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.m_container.SetCookies(URI, cookie);
//clientSideTab.Headers.Add(HttpRequestHeader.Cookie, cookie);
String resultJSON = clientSideTab.UploadString(URI,"POST", jsonData);
this worked for me. hope this will help you.

PHP service to C#

in php i post a request like
$.post("/service.php?cat=c1", {
group: $this.attr('href'),
})
where group -> #$!/mycat/year,2012
now i want to do same request in c#
var httpWebRequest = (HttpWebRequest)WebRequest.Create( url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
I tried
String url = domain + "./service.php?cat=c1&group=%22#$!/mycat/year,2012%22";
and
String url = domain + "./service.php?cat=c1&group=mycat&year=2012";
but "message" always returns empty
What is the problem here?
You can use the WebClient class, as this is easier to use.
Pass in the values as NameValueCollection object
var client = new WebClient();
var nameValueCollection = HttpUtility.ParseQueryString("cat=c1&group=mycat&year=2012");
var response = client.UploadValues(domain + "/service.php","POST",nameValueCollection);
var responseStr = Encoding.ASCII.GetString(response);

Categories

Resources