the APi call (Patch) through Visual Studio Console app is failing with the following error
The remote server returned an error: (403) Forbidden.
The same call works fine when I use Postman. I get the response back from Postman(Basic authentication with username and password). What could be the issue with the c# program.
.NET framework 4.7
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var result = string.Empty;
string json = #"{
""schemas"": [
""urn:scim:schemas:core:2.0:User"",
""urn:scim:schemas:extension:fa:2.0:faUser""
],
""userName"": ""ZMatt.Dandon #cmpy.com"",
""name"": {
""familyName"": ""Dandon"",
""givenName"": ""ZMatt""
},
""displayName"": ""ZMatt Dandon"",
""preferredLanguage"": ""en"",
""active"": false
}";
string url = #"https://url/hcmRestApi/scim/Users/C8FF94E381891376E050480A69294891";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
Req.Credentials = new NetworkCredential("UserName", "Password");
//Content_type
Req.ContentType = "application/vnd.oracle.adf.action+json";
//HTTP method
Req.Method = "PATCH";
using (var streamWriter = new StreamWriter(Req.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)Req.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
}
Basic authentication is base64 encoded and added to the HTTP Authorization header.
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
//Req.Credentials = new NetworkCredential("00OracleERPuser", "PMT12345");
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes("UserName" + ":" + "Password"));
Req.Headers.Add("Authorization", "Basic " + encoded);
Related
I am trying to download a JSON string from a PHP file on my webserver with WebClient.
This is my code:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Web.Script.Serialization;
using System.Collections.Generic;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static bool GetProgramInfo (string secret_key)
{
try
{
ServicePointManager.ServerCertificateValidationCallback += Methods.ValidateRemoteCertificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(username, password);
client.Headers.Add(HttpRequestHeader.UserAgent, useragent);
string jsonData = client.DownloadString(url);
MessageBox.Show(jsonData);
}
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
}
I tried removing all code that has to do with JSON, including the using statements.
The program goes into break mode exactly at string jsonData = client.DownloadString(url); and I get the error System.ArgumentException: 'Invalid JSON primitive: .'. The error still shows when I try to use .ToString().
The PHP script returns the data from a SQL table as shown here:
$stmt = $conn->prepare("SELECT id, value FROM `kl_general`");
$stmt->execute();
while ($row = $stmt->fetch()) {
if (intval($row['id'] == 5))
$version = $row['value'];
else if (intval($row['id']) == 6)
$hash = $row['value'];
}
$jsonFormat = json_encode(array('version' => $version, 'hash' => $hash));
die($jsonFormat);
When I directly access the file on my server I get the indented results: {"version":"3.0.0","hash":"a28fa7bab9878e42121efccb4e9277a8"}
Update
I attempted using HttpClient instead of WebClient using the code below with the same error being produced:
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) }
using (var client = HttpClient(handler))
{
var result = client.GetStringAsync(url);
MessageBox.Show(result.Result);
}
I have created a c# library in Visual Studio 2019 on my mac. I am trying to expose a method in my dll which should have the capacity to make an http call and return the response.
But I am getting the error Cannot send a content-body with this verb-type.
I am very new to c#, so I just copy-pasted code from online. Please show me what wrong I am doing.
My Library,
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace ImageTrainer
{
public class Trainer
{
public static void TrainImage()
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("https://www.abcd.com/rest/city/search/Bang");
request.Method = "GET";
request.ContentType = "application/json";
// // request.ContentLength = DATA.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
// // requestWriter.Write(DATA);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
// responseReader.Close();
// Console.WriteLine(response);
}
}
}
and I am using the library in another console application.
using System;
using ImageTrainer;
namespace ImageTrainerTest
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Trainer.TrainImage();
}
}
}
What mistake am I making?
Remove these 2 lines:
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Close();
As you are making GET request, you should not have any body, otherwise you should use POST verb.
I am building a REST Client in C#. I am getting forbidden 403 error. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using restservice.webref;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace restservice
{
class getUUID
{
private const string URL = "http://XXX.XXXX.com/ws410/XXXXX/XX/XX";
public void getProductID()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.Credentials = new NetworkCredential("XXXX", "XX");
request.Accept = #"text/html, application/xhtml+xml, */*";
request.Referer = #"http://www.somesite.com/";
request.Headers.Add("Accept-Language", "en-GB");
request.UserAgent = #"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
request.Host = #"www.my.XXX.com";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentType = "application/json";
/*StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(false);
requestWriter.Close();*/
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
String htmlString = reader.ReadToEnd();
}
/*
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();*/
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
}
}
}
I have also given the credentials as well as enabled the default credentials. Still I get the 403 error.
Please can you help?
This might be related to Env. security profile . For example i had the same issue . Added below in spring security yml file securityCollections: - name: "Security" patterns: - "/rootpath/*"
Http Forbidden error usually occurs when you are trying to call the server and server is not allowing the request.
The API that you are calling should whitelist your application IP.
Check if there is any http header restrictions on the API that you are calling.
For Infra related changes you can check this: link
I'm trying to post a JSON string on a PHP page using HTTP response methods as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Web;
namespace http_requests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/abc/products.php");
//httpWebRequest.ContentType = "application/json";
//httpWebRequest.Method = "POST";
//using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
//{
// string json = new JavaScriptSerializer().Serialize(new
// {
// user = "Foo",
// password = "Baz"
// });
// streamWriter.Write(json);
// streamWriter.Flush();
// streamWriter.Close();
// var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
// {
// var result = streamReader.ReadToEnd();
// }
//}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/ABC/products.php");
request.Method = WebRequestMethods.Http.Post;
string DataToPost = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});
byte[] bytes = Encoding.UTF8.GetBytes(DataToPost);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
//string postData = "firstName=" + HttpUtility.UrlEncode(p.firstName) +
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
//StreamWriter writer = new StreamWriter(request.GetRequestStream());
//writer.Write(DataToPost);
//writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//StreamReader reader = new StreamReader(response.GetResponseStream());
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
richTextBox1.AppendText("R : " + result);
Console.WriteLine(streamReader.ReadToEnd().Trim());
}
//richTextBox1.Text = response.ToString();
}
}
}
I tried it in many different ways (converting to bytes too) but still posts a NULL array.
PHP Code:
<?php
$json = $_POST;
if (isset($json)) {
echo "This var is set so I will print.";
//var_dump($json);
var_dump(json_decode(file_get_contents('php://input')));
}
?>
When I try to get tha response from server and print onto a text box, it prints right:
R : This var is set so I will print.object(stdClass)#1 (2) {
["user"]=>
string(3) "Foo"
["password"]=>
string(3) "Baz"
}
but i'm unable to check it on my PHP page, it says:
This var is set so I will print.NULL
Not sure if its posting a JSON onto PHP or not, but it sure does posts a NULL.
I want to see the JSON on PHP page, Any help would be appreciated.
Thank you,
Revathy
There is nothing wrong with your c# client side code, the problem is that visiting a site in your browser is a seperate request from the c# post, so you wont see anything.
As per my comment, if you want to see the data in a browser after a post i c#, you will need to save and retrieve it.
Here is a simple example using a text file to save post data and display it:
//if post request
if($_SERVER['REQUEST_METHOD']=='POST'){
//get data from POST
$data = file_get_contents('php://input');
//save to file
file_put_contents('data.txt', $data);
die('Saved');
}
//else if its a get request (eg view in browser)
var_dump(json_decode(file_get_contents('data.txt')));
I keep on getting the exception The remote server returned an error: (400) Bad Request. Whenever it comes at the HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;. Can someone please help me? Here's my code. By the way, it's just a single aspx with not html content. It's just a pure C# file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace Facebook_API
{
public partial class Facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "1234567891234567"; //Just placed this digits to keep this hidden
string app_secret = "12345678912345678912345678912345"; //Just placed this digits to keep this hidden
string scope ="publish_stream,manage_pages"; //Scope are the permissions
if( Request["code"] == null)
{
Response.Redirect(String.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret{4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach(string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1 ));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "Testing Facebook WebAPI " });
}
}
}
You can also try this code by simple creating a new project and create a webform the just insert this in the cs file.
Why are you using
request.Method = "Put";
instead of a normal GET request?