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).
Related
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.
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);
});
I am trying to implement Vault of Satoshi's API in Google App Engine Go. Their reference API is in PHP:
<?php
$serverURL = 'https://api.vaultofsatoshi.com';
$apiKey = 'ENTER_YOUR_API_KEY_HERE';
$apiSecret = 'ENTER_YOUR_API_SECRET_HERE';
function usecTime() {
list($usec, $sec) = explode(' ', microtime());
$usec = substr($usec, 2, 6);
return intval($sec.$usec);
}
$url = 'https://api.vaultofsatoshi.com';
$endpoint = '/info/currency';
$url = $serverURL . $endpoint;
$parameters= array();
$parameters['nonce'] = usecTime();
$data = http_build_query($parameters);
$httpHeaders = array(
'Api-Key: ' . $apiKey,
'Api-Sign:' . base64_encode(hash_hmac('sha512', $endpoint . chr(0) . $data, $apiSecret)),
);
// Initialize the PHP curl agent
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "something specific to me");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
My Go code looks like this:
func GenerateSignatureFromValues(secretKey string, endpoint string, values url.Values) string {
query:=[]byte(values.Encode())
toEncode:=[]byte(endpoint)
toEncode = append(toEncode, 0x00)
toEncode = append(toEncode, query...)
key:=[]byte(secretKey)
hmacHash:=hmac.New(sha512.New, key)
hmacHash.Write(toEncode)
answer := hmacHash.Sum(nil)
return base64.StdEncoding.EncodeToString(([]byte(strings.ToLower(hex.EncodeToString(answer)))))
}
func Call(c appengine.Context) map[string]interface{} {
serverURL:="https://api.vaultofsatoshi.com"
apiKey:="ENTER_YOUR_API_KEY_HERE"
apiSecret:="ENTER_YOUR_API_SECRET_HERE"
endpoint:="/info/order_detail"
tr := urlfetch.Transport{Context: c}
values := url.Values{}
values.Set("nonce", strconv.FormatInt(time.Now().UnixNano()/1000, 10))
signature:=GenerateSignatureFromValues(apiSecret, endpoint, values)
req, _:=http.NewRequest("POST", serverURL+endpoint, nil)
req.Form=values
req.Header.Set("Api-Key", apiKey)
req.Header.Set("Api-Sign", signature)
resp, err:=tr.RoundTrip(req)
if err != nil {
c.Errorf("API post error: %s", err)
return nil
}
defer resp.Body.Close()
body, _:= ioutil.ReadAll(resp.Body)
result := make(map[string]interface{})
json.Unmarshal(body, &result)
return result
}
Both of those pieces of code generate the same signature for the same input. However, when I run the PHP code (with the proper Key and Secret), the server responds with a proper response, but while I run the Go code, the server responds with "Invalid signature". This error indicates that the HTTP request generated by Go must be somehow malformed - either HTTP Header's values are wrong (if the header values are completely missing a different error appears), or the way the POST fields are encoded is wrong for some reason.
Can anyone help me find some reason why those two pieces of code generate different HTTP requests and how can I make Go generate requests like the PHP code?
See the documentation for Request.Form:
// Form contains the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values
Specifically "HTTP client ignores Form and uses Body instead."
With this line:
req, _:= http.NewRequest("POST", serverURL+endpoint, nil)
You should use this instead of nil:
bytes.NewBufferString(values.Encode())
Also keep in mind that the order of map is not guaranteed. url.Values is map[string][]string. So you should be using Encode() once and use the same result in the body and signature. There is a chance that by using Encode() twice the order could be different. This is an important difference between Go and PHP.
You should also make a habit of handling error instead of ignoring it.
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();
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);