I am trying get string result from PHP webservice in my android application, I used ksaop2 library and this is my code :
env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
request = new SoapObject("customWebService","addProductToCart");
request.addProperty("sessionID", sessionId);
request.addProperty("cartID", cartID);
request.addProperty("productID", productID);
request.addProperty("qty", qty);
request.addProperty("sku", productSKU);
env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(
"http://mysiteeee.com/WebServiceSOAP/server.php?wsdl/",
60000);
androidHttpTransport.debug = true;
androidHttpTransport.call("", env);
result = env.getResponse();
It`s returned this:
???·???§?? ?¯?²?????? (???§??) ?§???²?§???? ????µ???? ?±?§ ???´?®?µ ?©?????¯.
I tested it on Chrome and Firefox with UTF-8 encoding and shows result correctly on browser.
How can I get result from web service with correct encoding and show it on android?
Try getting response this way :
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
String Test1 = result.getProperty(0).toString();
Edit : Try setting Xml header Tag for request :
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
Related
I have a work to do and I need to login to the webpage, and extract content from it.
The query has to be made of a username and an access key.
The problem is that I don't really know how to make a query with thos 2 elements, and in PHP.
So, I have found this code have this code :
$ak = "accesskey";
$username = 'admin';
$password = '123';
$remote_url = 'http://192.168.1.78/index.php';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Basic " . base64_encode("$username:$ak")
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);
print($file);
But the output is simply the Webpage code, from the <!DOCTYPE html><html> to </html>
According to the webpage REST API, the result that I need to get is this :
{
success: true,
result: json_result
}
Any idea why it doesn't work ?
PS : here is the API documentation : https://www.vtiger.com/docs/rest-api-for-vtiger#/Authentication
The vTiger API (in 7.2 at least) has an odd combination of parameter and form POST payloads. Here is the Python script I used to get started. Note that it uses param in the getchallenge hit but data in the login hit:
import requests
from hashlib import md5
import urllib3
urllib3.disable_warnings() # shut up whining about that security stuff
encoding = 'ascii'
userName = 'Michael'
userToken = (access key from my preferences page)
APIURL='https://our.crm.instance/webservice.php'
session = requests.Session()
def getSession(session, name, token):
response = session.get(APIURL, params={'operation':'getchallenge', 'username':userName}, verify=False)
token_key = response.json()['result']['token']
combined = token_key + userToken
accessKey = md5(combined.encode(encoding)).hexdigest()
response1 = session.post(APIURL,
data={'operation':'login', 'username':userName, 'accessKey':accessKey},
verify=False)
return response1.json()['result']['sessionName']
sessionToken = getSession(session, userName, userToken)
types = session.get(APIURL, params={'operation':'listtypes', 'sessionName':sessionToken})
print(types.json())
I'm using Guzzle with Laravel to get an object from external API with a HTTP. The API return XML Object similar to this (https://www.w3schools.com/php/note.xml)
I need to check one value of the response body. Here is my code:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
echo $stringBody;
which is working fine, I mean it display the body as below picture
but I couldn't get one value?
I tried different methods but non of them is working!
for example, this way:
$result = starts_with($stringBody, 'Tove');
or
splitName = explode(' ', $res->getBody());
$first_name = $splitName[0];
echo $first_name;
non is working? I think it consider the body text empty ?
I tried using json_decode but it doesn't work or not supported anymore.
Any idea?
Thanks
What you get from response is xml content. Due to browser compatibility with XML you see only text. You just need SimpleXML class of php for get content as per XML node. Here is sample code
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
$xml = simplexml_load_string($stringBody);
echo $xml->to;
Hope this help you.
The issue is, that I am sending a JSON file in a POST request but i don't know how to get the data from the request itself
Here is the python script that sends the POST request:
import json
import httplib
filepath = 'example.txt'
with open(filepath) as fp:
line = fp.readline()
line2 = fp.readline(9)
jsonbaloo = {}
jsonbaloo["name"] = line
jsonbaloo["score"]= line2
result = json.dumps(jsonbaloo)
def post_dict():
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('altrevista.org')
conn.request("POST", "/", result, headers)
post_dict()
I want to get the JSON data server side, so I can put it on an SQL database, but I can't program in PHP.
PHP SCRIPT:
<?php
function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
}
?>
conn.read() to get the response back
Since you're writing to a file, you can read from the file using PHP with fopen() or file_get_contents().
Using fopen():
$fileHandle = fopen("path/to/example.txt", "r");
Using file_get_contents():
$fileString = file_get_contents("path/to/example.txt");
You should receive the data using file_get_contents (php://input stream) and convert it to an array using json_decode.
// Retrieve the Post JSON data
$input = file_get_contents('php://input');
// Convert to json to array
$array = json_decode($input, true);
// View the content of the array
print_r($array);
My application (written in vb.net) send data to a php script hosted on one of the free webhosting servers. The php script evaluates the data, and responds accordingly. The response from the server looks something like this:
Valid
<!-- Hosting3322 Analytics Code -->
<script type="text/javascript" src="theurlforthewebsite/count.php"></script>
<!-- End of Analytics Code -->
'Valid' is from my php script. Rest of is a little script by the server that they hide in every page.
Here is the php script:
<?php
$d = $_POST['mac'];
if($d=='45bgd0434')
echo "Valid";
else
echo "Invalid";
?>
Here is my vb.net code:
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create("http://sitename.com/verify.php")
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "mac=45bgd0434"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
MessageBox.Show(responseFromServer)
I would just like to have only the output and not that extra code. Is there any way I can use an alternative method to print in PHP, or probably another method with which I can talk to the server?
I have tried other free servers on the internet, but they all seem to put in some code. Would really appreciate your help.
I'm trying to parse the xml response from a soap service. However, I can't get simplexml_load_string to work! Here is my code:
//make soap call
objClient = new SoapClient('my-wsdl',
array('trace' => true,'exceptions' => 0, 'encoding' => 'UTF-8'));
$soapvar = new SoapVar('my-xml', XSD_ANYXML);
$objResponse = $objClient->__soapCall($operation, array($soapvar));
//process result
$str_xml = $objClient->__getLastResponse();
$rs_xml = simplexml_load_string($str_xml);
...$rs_xml always has just one element with name Envelope.
However, if I use *"print var_export($objClient->__getLastResponse(),true);"* to dump the result to my browser, then cut and paste it into my code as a string variable, it work fine! This is what I mean:
$str_xml = 'my cut and pasted xml';
$rs_xml = simplexml_load_string($str_xml);
So it seems the problem is somehow related to something $objClient->__getLastResponse() is doing to the string it creates... but I'm at a loss as to what the problem is or how to fix it.
Do the following:
$str_xml = $objClient->__getLastResponse();
$str_xml = strstr($str_xml, '<');
$rs_xml = simplexml_load_string($str_xml);
As it's a quick and easy hack to strip off stuff before the first opening element.