HTTP POST is giving unauthorized 401 Exception - c#

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.

Related

C# httpwebrequest is only sending GET requests even when method is set to POST

I'm using Xamarin C# and php to create a simple android app that sends coordinate data to an apache sql database. When I use httpwebrequest to send a POST request to the server php, it sends a GET instead. Even though I set the request type to POST. The strange thing is that other requests that I have used using the exact same code work okay, this one specifically isn't working.
public class gpsGetterScript{
public static double longitude;
public static double latitude;
public static SimpleLocationManager locationManager = new SimpleLocationManager();
public static void startGetLocation()
{
Timer timer = new Timer();
timer.Interval = 6 * 1000;
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
double lon = locationManager.LastLocation.Longitude;
double lat = locationManager.LastLocation.Latitude;
longitude = lon;
latitude = lat;
Console.WriteLine(lon.ToString());
Console.WriteLine(lat.ToString());
Dictionary<string, string> gpsData = new Dictionary<string, string>();
gpsData.Add("longitude", lon.ToString());
gpsData.Add("latitude", lat.ToString());
gpsData.Add("device_owner", "Test");
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
var contentType = "application/json";
//var contentType = "application/x-www-form-urlencoded";
httpRequest.ContentType = contentType;
var data = JsonConvert.SerializeObject(gpsData);
//var data = "longitude=" + lon.ToString() + "&latitude=" + lat.ToString() + "&device_owner=" + "Test";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
Console.WriteLine(data.ToString());
Console.WriteLine(httpRequest.RequestUri.ToString());
Console.WriteLine(httpRequest.Headers);
Console.WriteLine(httpRequest.Method);
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
locationManager.StartLocationUpdates(LocationAccuracy.Balanced, 5, TimeSpan.FromMinutes(.5), TimeSpan.FromSeconds(20));
SimpleLocationLogger.Enabled = true;
}
}
here is one of the httprequests from a related project that does work (same server being used)
public static string sendLoginRequest(string email, string password)
{
var url = "theURL";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
var data = "email=" + email + "&password=" + password;
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
I know it is the app sending the wrong request, as when I made the php echo the request type it came back as GET. Strangely, when I use reqbin to make the POST request using the same URL, it works fine. It really is just for some reason the request in C# is not sending a POST. The other question about this was resolved by adding a www. to the api url, but that did not work for me.
UPDATE: 4/20/2022- Here is the php code
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once '../../../Database.php';
include_once '../location_obj.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$database = new Database();
$db = $database->getConnection();
$data = json_decode(file_get_contents("php://input"));
$item = new location_obj($db);
$stmt = $item->InputCoordinates();
$item->longitude = $data->longitude;
$item->latitude = $data->latitude;
$item->device_owner = $data->device_owner;
if ($item->InputCoordinates()) {
echo json_encode(array("message" => "Successfully", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
else {
echo json_encode(array("error" => "failed! Check your data and try again.", "data" => $item, "Request Type" => $_SERVER['REQUEST_METHOD']));
}
}
else {
echo json_encode(array("error" => "Only the POST method is supported!", "Request Type" => $_SERVER['REQUEST_METHOD']));
}
?>`
I get the error {"error":"Only the POST method is supported!","Request Type":"GET"} but when I use reqbin I get "message": "Successfully", "data": { "longitude": "theLongitude", "latitude": "theLatitude", "device_owner": "Test" }, "Request Type": "POST"
I checked the url that is used using Console.WriteLine(url); , it is the right one.
I fixed it, seems I forgot to add a / at the end of the URL. It was https://example.com/api/v2/location/input instead of https://example.com/api/v2/location/input/

HTTP Post Authentication error

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

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}");
}

Getting error : Could not create SSL/TLS secure channel

I am creating Shutterstock web application for searching images.
take a look on the code
function createImageComponent(image) {
var wrapper = $('<div>');
var thumbWrapper = $('<div>');
var thumbnail = $('<img>');
var description = $('<p>');
$(thumbnail).attr('src', image.assets.preview.url);
$(thumbWrapper)
.addClass('thumbnail-wrapper')
.css('height', image.assets.)
.css('width', image.assets.preview.width)
.append(thumbnail);
$(description)
.text(image.description)
.attr('title', image.description);
$(wrapper)
.addClass('media-wrapper image')
.append(thumbWrapper)
.append(description);
return wrapper;
}
// Create video wrapper component
function createVideoComponent(video) {
var wrapper = $('<div>');
var preview = $('<video>');
var description = $('<p>');
$(preview)
.attr('src', video.assets.thumb_mp4.url)
.attr('controls', true)
.attr('autoplay', true);
$(description)
.text(video.description)
.attr('title', video.description);
$(wrapper)
.addClass('media-wrapper video')
.append(preview)
.append(description);
return wrapper;
}
// Search media by type
function search(opts, media_type) {
var $container = $('#' + media_type + '-search-results');
var createComponentFunc = media_type === 'image' ? createImageComponent : createVideoComponent;
// Get Client ID and Client Secret for use in the Authorization header
var clientId = $('input[name=client_id]').val();
var clientSecret = $('input[name=client_secret]').val();
var jqxhr = $.ajax({
url: 'https://api.shutterstock.com/v2/' + media_type + 's/search',
data: opts,
headers: {
// Base 64 encode 'client_id:client_secret'
Authorization: 'Basic ' + window.btoa(clientId + ':' + clientSecret)
}
})
.done(function(data) {
if (data.total_count === 0) {
$container.append('<p>No Results</p>');
return;
}
$.each(data.data, function(i, item) {
var component = createComponentFunc(item);
$container.append(component);
});
})
.fail(function(xhr, status, err) {
alert('Failed to retrieve ' + media_type + ' search results:\n' + JSON.stringify(xhr.responseJSON, null, 2));
});
return jqxhr;
}
// On Page Load
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
// Clear current media results
$('#image-search-results, #video-search-results').empty();
// Serialize form options
var opts = $("input[value != '']", this).serialize();
// Search and display images
search(opts, 'image');
// Search and display videos
search(opts, 'video');
return false;
});
});
This code is for searching images using shutterstock basic authentication.I want to create it using c#.
and i am using the following code :
LoadHttpPageWithBasicAuthentication(#"https://api.shutterstock.com/v2/images/232713811?view=full", "ClientID", "Clientsecrate");
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;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
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;
}
But i am getting the error
The request was aborted: Could not create SSL/TLS secure channel.
Please help what is the error stuck with this problem.
This was happening for me also for the shutterstock API .try to put this code
try
{
var request = (HttpWebRequest)WebRequest.Create("https://api.shutterstock.com/v2/images/232713811?view=full");
var username = "YourClientID";
var password = "YourClientSecrate";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
// Image myojb = (Image)js.Deserialize(objText, typeof(Image));
var myojb = JsonConvert.DeserializeObject<RootObject>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
You need to Deserialize the response data as what result you want.

Box API Create Shared link

I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;

Categories

Resources