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);
}
Related
I send a request on the API, the request and the response are successful, but I want to get the value equivalent to the authentication keyword through the response. How can I do that? I tried this way on the examples I found, but it doesn't give any results .Net 6.0
using LoggerApi.Login;
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Extensions.Primitives;
namespace LoggerApi.Login
{
public class AdminLogin
{
public async static Task<object> GetAuthenticationCode()
{
var client = new HttpClient();
var loginEndpoint = new Uri("https://admin.com/login");
var loginPayload = new LoginPayload()
{
Username = "admin",
Password= "admin",
};
var requestJson = JsonConvert.SerializeObject(loginPayload);
var payload = new StringContent(requestJson, Encoding.UTF8, "application/json");
var res = await client.PostAsync(loginEndpoint, payload).Result.Headers.TryGetValues("authentication");
return res;
}
}
}
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);
I want to save complete web page asp in local drive by .htm from url or url but I did not success.
Code
public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource)
{
//--------- Download Complete ------------------
// using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
// {
//client
//HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource);
//webRequest.AllowAutoRedirect = true;
//var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource);
//client1.CookieContainer = new System.Net.CookieContainer();
// client.DownloadFile(link_Pagesource, #"D:\S1.htm");
// }
//--------- Download Page Source ------------------
HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com");
URL_pageSource.Timeout = 360000;
//URL_pageSource.Timeout = 1000000;
URL_pageSource.ReadWriteTimeout = 360000;
// URL_pageSource.ReadWriteTimeout = 1000000;
URL_pageSource.AllowAutoRedirect = true;
URL_pageSource.MaximumAutomaticRedirections = 300;
using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse())
{
str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8);
pagesource1 = str_PageSource.ReadToEnd();
success = true;
}
Error :
Too many automatic redirections were attempted.
Attemp by this codes but not successful.
many url is successful with this codes but this url not successful.
here is the way
string url = "https://www.digikala.com/";
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
}
and result variable will contains the page as HTML then you can save it to a file like this
System.IO.File.WriteAllText("path/filename.html", result);
NOTE you have to use the namespace
using System.Net.Http;
Update if you are using legacy VS then you can see this answer for using WebClient and WebRequest for the same purpose, but Actually updating your VS is a better solution.
using (WebClient client = new WebClient ())
{
string htmlCode = client.DownloadString("https://www.digikala.com");
}
using (WebClient client = new WebClient ())
{
client.DownloadFile("https://www.digikala.com", #"C:\localfile.html");
}
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')));
A month ago a build a twitter tool in c# Windows Form Application. I can send tweets and view the hometimeline,friendtimeline and the mentiontimeline. I used the twitterizer dll with the OAuthTokens method, but there is a refresh limit and it is very slow.
Now i want to start a streaming twitter application but i cant find a proper example or documentation for this. I started but i didn't find the function who can start the stream and but it in a string or textbox. My question is how to get the stream from the hometimeline.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Twitterizer;
using Twitterizer.Streaming;
namespace Twww
{
public partial class Form1 : Form
{
public OAuthTokens tokens = new OAuthTokens();
private string userAgent = null;
public Form1()
{
InitializeComponent();
/* input tokens removed in example code */
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
}
private void Form1_Load(object sender, EventArgs e)
{
Twitterizer.Streaming.UserStreamOptions options = new UserStreamOptions();
OAuthTokens token = new Twitterizer.OAuthTokens ();
TwitterStream stream = new TwitterStream(token, userAgent, options);
}
}
}
I tried to make it work for a user stream, but i get 401 or 403 errors, who says i have no rights
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Twitterizer;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
OAuthTokens tokens = new OAuthTokens();
string consumerKey = "XX";
string consumerSecret = "XX";
string accessToken = "XX";
string accesssecret = "XX";
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
string url = "https://userstream.twitter.com/1.1/user.json?with=followings&replies=all";
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("XX", "XX");
StreamReader reader = new StreamReader(wc.OpenRead(url));
string line;
while ((line = reader.ReadLine()) != null)
{
dynamic json = JsonConvert.DeserializeObject(line);
if (json.text != null)
{
Console.WriteLine(json.text);
}
}
}
}
}
Check this, you have a very well designed guide of TwitterStream in twitterizer:
http://thewayofcode.wordpress.com/tag/json/