equal of php in asp.net - php

what is the equivalent code in asp.net language???
<?php
$ch = curl_init("http://irnafiarco.com/queue");
$request["queue"] = file_get_contents("/path_to_my_xml_file/my_xml_file.xml");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($ch);
curl_close ($ch);
echo $response;
?>
in http://irnafiarco.com/queue a Listener that get requst xml file and saver xml file.

Using WebRequest, this will be the basic code
var req = WebRequest.Create(#"http://irnafiarco.com/queue"))
// prepare the request
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
// push the file contents into request body
var data = "queue=" + System.IO.File.OpenText(filePath).ReadToEnd();
var bytes = System.Text.Encoding.Ascii.GetBytes(data );
request.ContentLength = bytes.Length;
var rs = req.GetRequestStream();
rs.Write(bytes, 0, bytes.Length);
rs.Close ();
// get the response
var resp = req.GetResponse();
var sr = new System.IO.StreamReader(resp.GetResponseStream());
var result = sr.ReadToEnd();
Disclaimer: untested code
EDIT:
Added the post parameter name ("queue") which I have missed in first draft. Also added content-length for the request. This code should get you started. The basic idea is you need to simulate exact post request generated by PHP code. Use tool such as Fiddler/ Firebug on FF to inspect & compare request/response from PHP and .NET code.
Further, I suspect that the PHP code may generating request with content type as multipart/form-data. However, I believe that server should also able to support the post body with application/x-www-form-urlencoded (because we have only one parameter in body) but in case it doesn't work and you must generate POST body as multipart/form-data then it will be little more involved. See this SO question where accepted answer has given the sample code for the same : Upload files with HTTPWebrequest (multipart/form-data)

Take a look at WebRequest, WebProxy classes which are inline with what you're after...
WebRequest request = WebRequest.Create(url);
request.Proxy = new WebProxy("http://blahblahblah", true)
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// handle response here
Also, see here, and here, though may not be relevant for your implementation
Examples of using these to fetch XML abound, i.e.:
System.Net.HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("yourURL.xml");
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
System.Net.HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
System.IO.Stream responseStream = webResponse.GetResponseStream();
System.Xml.XmlTextReader reader = new XmlTextReader(responseStream);
//Do something meaningful with the reader here
reader.Close();
webResponse.Close();

Related

screenshot using googlepagespeed api

Below is my code to capture the screenshot of of webpage. But i get the output of the same as how in the image below. Kindly suggest on what is the mistake i am committing. Also kindly suggest the method to save this screenshot to the server?
<?php
$url='https://www.google.com';
$stratedy = 'mobile' ;
$apiReqUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';
$apiKey = 'my_api_key' ;
$curl = curl_init();
curl_setopt($curl, CURL_OPTURL, $apiReqUrl.'?url='.$reqUrl.'
&key='.$apiKey.'&screenshot=true&strategy='.$stratedy);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($curl);
$data = json_decode($result, true);
$img = str_replace(array('_','-'), array('/','+'), $data['screenshot']
['data']);
echo '<img src="data:image/jpeg;base64,'.$img.'">';
?>
If you can, try using the HTML version from Generating Screenshots of URLs using Google's secret magic API. All you need to do is to call the API and it's free (I guess).
For example in PHP:
<?php
$url = "https://praveen.science/";
// Hit the Google PageSpeed Insights API.
// Catch: Your server needs to allow file_get_contents() to make this run. Or you need to use cURL.
$response = file_get_contents('https://www.googleapis.com/pagespeedonline/v2/runPagespeed?screenshot=true&url='.urlencode($url));
// Convert the JSON response into an array.
$googlePagespeedObject = json_decode($response, true);
// Grab the Screenshot data.
$screenshot = $googlePagespeedObject['screenshot']['data'];
// Fix url encoded base64
$screenshot = str_replace(array('_','-'), array('/','+'), $screenshot);
// Build the Data URI scheme and spit out an <img /> Tag.
echo "<img src=\"data:image/jpeg;base64,{$screenshot}\" alt=\"Screenshot\" />";
// Or.. base64 decode and store
file_put_contents('...', base64_decode($screenshot));
Or in JavaScript:
$(function() {
// Get the URL.
var url = "https://praveen.science/";
// Prepare the URL.
url = encodeURIComponent(url);
// Hit the Google Page Speed API.
$.get("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + url, function(data) {
// Get the screenshot data.
var screenshot = data.screenshot;
// Convert the Google's Data to Data URI scheme.
var imageData = screenshot.data.replace(/_/g, "/").replace(/-/g, "+");
// Build the Data URI.
var dataURI = "data:" + screenshot.mime_type + ";base64," + imageData;
// Set the image's source.
$("img").attr("src", dataURI);
});
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<h1>Hard Coded Screenshot of my Website:</h1>
<img src="//placehold.it/300x50?text=Loading+Screenshot..." alt="Screenshot" />
There are a lot of APIs available on the internet to take screenshots. Something like https://www.purplescreenshots.com/ has example of integrating screenshots too.

how to get unknown string in $_GET method through URL

I want to pass a string from one PHP file to another using $_GET method. This string has different value each time it is being passed. As I understand, you pass GET parameters over a URL and you have to explicitly tell what the parameter is. What if you want to return whatever the string value is from providing server to server requesting it? I want to pass in json data format. Additionally how do I send it as Ajax?
Server (get.php):
<?php
$tagID = '123456'; //this is different every time
$tag = array('tagID' => $_GET['tagID']);
echo json_encode($tag);
?>
Server (rec.php):
<?php
$url = "http://192.168.12.169/RFID2/get.php?tagID=".$tagID;
$json = file_get_contents($url);
#var_dump($json);
$data = json_decode($json);
#var_dump($data);
echo $data;
?>
If I understand correctly, you want to get the tagID from the server? You can simply pass a 'request' parameter to the server that tells the server what to return.
EDIT: This really isn't the proper way to implement an API (like, at all), but for the sake of answering your question, this is how:
Server
switch($_GET['request']) {
case 'tagID';
echo json_encode($tag);
break;
}
You can now get the tagID with a URL like 192.168.12.169/get.php?request=tagId
Client (PHP with CURL)
When it comes to the client it gets a bit more complicated. You mention AJAX, but that will only work for JavaScript. Your php file can't use AJAX, you'll have to use cURL.
$request = "?request=tagID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '192.168.12.169/get.php' . $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
EDIT: added the working cURL example just for completeness.
Included cURL example from: How to switch from POST to GET in PHP CURL
Client (Javascript with AJAX)
$.get("192.168.12.169/get.php?request=tagId", function(data) {
alert(data);
});

How to rewrite this POST curl script in python?

I'm going to rewrite this POST request in python:
<?php
// Set these variables
$networkid = ""; // In your HasOffers system at Support -> API
$apikey = ""; // In your HasOffers system at Support -> API
$offerid = "0"; // Specify an offer ID to add the creative to
$creativetype = "image banner"; // Types: file, image banner, flash banner, email creative, offer thumbnail, text ad, html ad, hidden
$filename = "banner_728x90.gif"; // File name; no spaces, and file must be in same directory as this script
$display = $filename; // Or change this to the "display name" for this creative
// Don't change anything below here
$creativetype = urlencode($creativetype);
$display = urlencode($display);
$fields[$filename] = "#{$filename}";
$url = "http://api.hasoffers.com/v3/OfferFile.json?Method=create&NetworkToken={$apikey}&NetworkId={$networkid}&data[offer_id]={$offerid}&data[type]={$creativetype}&data[display]={$display}&return_object=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$resp = curl_exec($ch);
curl_close($ch);
print_r(json_decode($resp, true)); // Final output; remove or change this if you want
?>
As I know, in pycurl the CURLOPT_POSTFIELDS attribute is absent. What can I use instead?
Thank you!
there are many python libraries that can be used:
http.client
https://docs.python.org/3.1/library/http.client.html
requests
https://pypi.python.org/pypi/requests/
the commands are pretty straightforwards:
using http.client:
import http.client
conn = http.client.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print(res.status, res.reason)
200 OK
or requests:
import requests
r = requests.get('https://github.com/timeline.json')
print r.json
Using HTTP client, a simple POST request may be done as follows:
connect = http.client.HTTPSConnection("base_url")
connect.request('POST', '/rest/api/'+ you_can_add_variables+ '/users?userEmail=' + another_variable, headers=headers)
Using requests:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
the documentation provided above should not prove difficult to understand

php - send and receive xml documents

I am trying to get a xml document back from the webserver that also supports php.
It's something similar to what the traditional web services do but i want to achieve it in php. Is this even possible?
To be more specific about my needs -
I want to send a xml document as a request to the server, have PHP do some processing on it and send me back an xml document as a response.
Thanks in advance.
Maybe you simply want http://php.net/SOAP ?
If not SOAP, then you can send your XML POST request and use $xml = file_get_contents('php://input'); to dump it to a variable that you can feed to http://php.net/DOM or other XML processors.
After processing, you header('Content-Type: text/xml'); (or application/xml) and output the modified XML document.
Super simple example of reading an XML request body:
$request = http_get_request_body();
if($request && strpos($request, '<?xml') !== 0){
// not XML do somehting appropriate
} else {
$response = new DomDocment(); // easier to manipulate when *building* xml
$requestData = DomDocument::load($request);
// process $requestData however and build the $response XML
$responseString = $response->saveXML();
header('HTTP/1.1 200 OK');
header('Content-type: application/xml');
header('Content-length: ', strlen($responseString));
print $responseString;
exit(0);
}
use curl.
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xmlString);
//execute post
$result = curl_exec($ch);

Help to convert this PHP code to VB.NET code

I have a code to send XML via POST. But this code is in PHP and I need it in VB.NET.
Any help to convert this code?
$XMLFile= (here i have created the xml file. XML is encoded ISO-8859)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"URL WHERE I SEND XML");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,"XMLDATA=".$XMLFile);
$results=curl_exec ($ch);
curl_close ($ch);
$results=stripslashes($results);
$xmlreturned=new SimpleXMLElement($results);
if($xmlreturned->NotificationResultHeader->RRC==0){
if($xmlreturned->NotificationResultList->NotificationResult->NRC==0){
echo "OK. SUCCES";
And how I convert this PHP code too:
$msg=htmlentities($msg);
$msg=urlencode($msg);
You need to use the HttpWebRequest and HttpWebResponse classes. The code could would look something like this (my VB is a bit rusty these days):
Dim xmlDoc as XmlDocumnet
'
' prepare you xml doc here...
'
Dim encoding as ASCIIEncoding = New ASCIIEncoding()
Dim postData as String
postData = "XMLDATA=" + xmlDoc.ToString()
Dim data() as Byte
data = encoding.GetBytes(postData)
' Prepare web request...
Dim myRequest as HttpWebRequest
myRequest = CType(WebRequest.Create("URL TO POST HERE"), HttpWebRequest)
myRequest.Method = "POST"
myRequest.ContentType="application/x-www-form-urlencoded"
myRequest.ContentLength = data.Length
Dim newStream as Stream = myRequest.GetRequestStream()
' Send the data.
newStream.Write(data, 0, data.Length)
' Get the response
Dim myResponse as HttpWebResponse
myResponse = myRequest.GetResponse()
See: htmlentities solution and urlencode solution
And as far as curl, it looks like you're trying to call a web service. If it's a proper web service (meaning there is a WSDL and an XSD somewhere), you should add a Service Reference (or a Web Reference if you're in VS2005 or VS2003) to your project, which will generate a proxy for you to use (instead of manually dumping XML to a server).

Categories