I want to send data from my Android app to my server.
On the client-side, meaning the application,I can create the JSON object and send it to the server.
The problem is, I don't know how to 'handle' it on the server side.All I want my server to do is to receive the JSON, parse it, and show it to me.That's it.
I know it's pretty vague question, but I don't really know where to start here, and would love if anyone could show me a complete tutorial.
Thanks!
Use PHP and json_decode()
http://php.net/manual/en/function.json-decode.php
Here a quick example how to handle the data:
// get json
$input = json_decode($_GET["json"]);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}
I used the GET parameter in this example. If you have larger data, use POST instead of GET.
Example:
URL: http://localhost/test/index.php?json={ "firstName" : "John","lastName" : "Doe","age" : 23 }
Output: Hello John Doe!
You are 23 years old! Wow.
But: Make sure you encode the JSON data at your application. In my example the browser does it.
// Some groovy code to dump an incoming request
import com.sun.net.httpserver.*;
HttpServer server = HttpServer.create(new InetSocketAddress(2228),0)
server.createContext('/', { HttpExchange exchange ->
println 'got a request'
println 'requestHeaders '+exchange.requestHeaders
println 'requestBody '+exchange.requestBody.text
exchange.sendResponseHeaders(200,0);
exchange.responseBody.write('hello from groovy land.'.bytes)
exchange.responseBody.close();
println 'all done'
} as HttpHandler)
server.start();
You can even use some shell script CGI file on the server. Here's a sample returning some fixed data to a JSONP request for testing something.
#!/bin/bash
#
# Handle a JSONP request for data returning a fake queue status result.
read -r -d '' DATA <<'EOF'
{
name: "TESTHOST",
status: "running",
items: [
{id:"4",status:"failed",title:"anadin map 2",user:"pat",progress:100},
{id:"2",status:"running",title:"silicon map",user:"tim",progress:52},
{id:"3",status:"queued",title:"anadin map",user:"pat",progress:0},
{id:"6",status:"queued",title:"neon calibration",user:"ian",progress:0}
]
}
EOF
CB=$(echo $QUERY_STRING | sed -n 's/.*jsoncallback=\([^&]*\).*$/\1/p')
DATA=${DATA/52/$(expr $RANDOM % 100)}
DATA="${CB}(${DATA});"
echo -e "content-type: application/json\r"
echo -e "content-length: ${#DATA}\r"
echo -e "x-test: $CB\r"
echo -e "\r"
echo "$DATA"
Substitute some parsing of the request data and return as appropriate.
Related
When i select audio morethen 30sec or 1min then its show below error
--> Sync input too long. For audio longer than 1 min use LongRunningRecognize with a 'uri' parameter.
-> https://speech.googleapis.com/v1p1beta1/speech:recognize?key="api key"
body -> {
"audio":{"content":" // base64 formated audio // "},
"config":{
"enableAutomaticPunctuation":true,
"encoding":"WEBM_OPUS",
"sampleRateHertz": 16000,
"languageCode":"en-US",
"model":"default"
}
}
You should use speech:longrunningrecognize endpoint for audio longer than 1 minute.
The endpoint with key is https://speech.googleapis.com/v1/speech:longrunningrecognize?key="api_key"
Using curl I can send a request to this endpoint:
curl -s -H "Content-Type: application/json" \
https://speech.googleapis.com/v1/speech:longrunningrecognize?key=AIzaSyD....\
-d "{
'config': {
'language_code': 'en-US'
},
'audio':{
'uri':'gs://cloud-samples-tests/speech/brooklyn.flac'
}
}"
Output:
{
"name": "1521059426290567438"
}
When a request is sent to the endpoint, it will create a long running operation and it will return a name. This will be used to check the status of the long running operation. You can check the status by sending a request to this endpoint https://speech.googleapis.com/v1/operations/<name>. If the operation is done, it will return the transcript in the response.
Check status:
curl -H "Content-Type: application/json; charset=utf-8" \
"https://speech.googleapis.com/v1/operations/1521059426290567438?key=AIzaSyD...."
Output:
I am trying to retrieve saved card details in android I implemented Razorpay payment gateway my requirement is to show user saved card details to the user how do I implement this.
this is what i done so far
val options = JSONObject()
options.put("name","Razorpay Corp")
options.put("description","Demoing Charges")
//You can omit the image option to fetch the image from dashboard
options.put("image","https://s3.amazonaws.com/rzp-mobile/images/rzp.png")
options.put("theme.color", "#3399cc");
options.put("currency","INR");
options.put("amount","50000")//pass amount in currency subunits
val retryObj = JSONObject()
retryObj.put("enabled", true)
retryObj.put("max_count", 4)
options.put("retry", retryObj)
val preFill = JSONObject()
preFill.put("email", "mitesh#yo.com")
preFill.put("contact", "9011111111")
options.put("prefill",preFill)
co.open(activity,options)
I find this question but a solution is not available that's why I am asking again
I don't know is it possible or not
Please help me any help would be helpful.
i asked this question to the razorpay team and they provide me the solution
you have to add customer id and save in your object so it will save your card detail
options.put("customer_id", "cust_4lsdkfldlteskf");
options.put("save", "1");
you can create customer using razorpay add customer api
below is the curl of add customer
curl -u <YOUR_KEY_ID>:<YOUR_KEY_SECRET> \
-X POST https://api.razorpay.com/v1/customers \
-H "Content-Type: application/json" \
-d '{
"name":"Gaurav Kumar",
"contact":"9123456780",
"email":"gaurav.kumar#example.com",
"fail_existing":"0",
"gstin":"29XAbbA4369J1PA",
"notes":{
"notes_key_1":"Tea, Earl Grey, Hot",
"notes_key_2":"Tea, Earl Grey… decaf."
}
}'
to retrieve card details you have to call fetch all tokens of customer api below is curl
curl -u <YOUR_KEY_ID>:<YOUR_KEY_SECRET> \-X GET https://api.razorpay.com/v1/customers/:customer_id/tokens
<YOUR_KEY_ID> is your key which start from rzp_***
<YOUR_KEY_SECRET> you have to generate from razorpay from website Setting>api keys
Hope this will solve your issue
I want to pull a file from my android device through an adb command from my macOS application.
Everything works perfect with the code below, except when the name of the file I want to pull contains special characters like german umlauts (äöüÄÖÜ).
I get this error:
adb: error: failed to stat remote object '/storage/emulated/0/Download/Böse': No such file or directory.
But when I use the command adb pull /storage/emulated/0/Download/Böse ~/Desktop from within the Terminal.app, the file will be pulled to my computer.
The strange thing here is that if I copy the substring /storage/emulated/0/Download/Böse from the Xcode console output, the command is also not working within the Terminal.app until I delete the ö and replace it with an ö from my keyboard input.
I tried replacing the ö with the unicode representation \u{00f6}, but this has no effect (but the console output still shows an ö but the 'wrong' encoded one.
// Configure task.
let task = Process()
task.launchPath = "~/Library/Android/sdk/platform-tools/adb"
task.arguments = ["pull", "/storage/emulated/0/Download/Böse", "~/Desktop"]
// Configure pipe.
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
// Run task.
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
// adb: error: failed to stat remote object '/storage/emulated/0/Download/Böse': No such file or directory
print(output)
I found the following in the documentation, how the Process handles the arguments that I provide:
The NSTask object converts both path and the strings in arguments to appropriate C-style strings (using fileSystemRepresentation) before passing them to the task via argv[] . The strings in arguments do not undergo shell expansion, so you do not need to do special quoting, and shell variables, such as $PWD, are not resolved.
It seems like I am not the only one with this problem, and I found this workaround:
How to work around NSTask calling -[NSString fileSystemRepresentation] for arguments, but I was not able to make it work with Swift.
As a workaround I am now writing my adb command to a file and execute it from a bash command in my application.
let source = "/storage/emulated/0/Download/Böse"
let destination = "~/Desktop"
guard let uniqueURL = URL(string: destination + "/" + ProcessInfo.processInfo.globallyUniqueString) else { return }
// Write command to file
let scriptContent = "#!/bin/bash\n~/Library/Android/sdk/platform-tools/adb pull -a \"" + source + "\" \"" + destination + "\""
try? scriptContent.write(to: uniqueURL, atomically: false, encoding: .utf8)
// Configure task.
let task = Process()
task.environment = ["LC_ALL": "de_DE.UTF-8", "LANG": "de_DE.UTF-8"]
task.launchPath = "/bin/bash"
task.arguments = [uniqueURL.path]
// Configure pipe.
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
try? task.run()
// Run task.
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
print(output)
Even though this is working for now, it is not a satisfactory solution as it is not very elegant and not efficient too, so any improvements or better answers are welcome.
I have got Apache2 Installed and Python working.
I am having a problem though. I have two pages.
One a Python Page and the other an Html Page with JQuery
Can someone please tell me how I can get my ajax post to work correctly.
<html>
<head>
</head>
<body>
<script>
$(function()
{
alert('Im going to start processing');
$.ajax({
url: "saveList.py",
type: "post",
data: {'param':{"hello":"world"}},
dataType: "application/json",
success : function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
And the Python Code
import sys
import json
def index(req):
result = {'success':'true','message':'The Command Completed Successfully'};
data = sys.stdin.read();
myjson = json.loads(data);
return str(myjson);
OK, let's move to your updated question.
First, you should pass Ajax data property in string representation. Then, since you mix dataType and contentType properties, change dataType value to "json":
$.ajax({
url: "saveList.py",
type: "post",
data: JSON.stringify({'param':{"hello":"world"}}),
dataType: "json",
success: function(response) {
alert(response);
}
});
Finally, modify your code a bit to work with JSON request as follows:
#!/usr/bin/python
import sys, json
result = {'success':'true','message':'The Command Completed Successfully'};
myjson = json.load(sys.stdin)
# Do something with 'myjson' object
print 'Content-Type: application/json\n\n'
print json.dumps(result) # or "json.dump(result, sys.stdout)"
As a result, in the success handler of Ajax request you will receive object with success and message properties.
You should read json data like this:
#!/usr/bin/env python3
import os
import sys
import json
content_len = int(os.environ["CONTENT_LENGTH"])
req_body = sys.stdin.read(content_len)
my_dict = json.loads(req_body)
With the following code, you can run into problems:
myjson = json.load(sys.stdin)
or written less succinctly:
requ_body = sys.stdin.read()
my_dict = json.load(requ_body)
That does work for me when my cgi script is on an apache server, but you can't count on that working in general--as I found out when my cgi script was on another server. According to the cgi spec:
RFC 3875 CGI Version 1.1 October 2004
4.2. Request Message-Body
Request data is accessed by the script in a system-defined method;
unless defined otherwise, this will be by reading the 'standard
input' file descriptor or file handle.
Request-Data = [ request-body ] [ extension-data ]
request-body = <CONTENT_LENGTH>OCTET
extension-data = *OCTET
A request-body is supplied with the request if the CONTENT_LENGTH is
not NULL. The server MUST make at least that many bytes available
for the script to read. The server MAY signal an end-of-file
condition after CONTENT_LENGTH bytes have been read or it MAY supply
extension data. Therefore, the script MUST NOT attempt to read more
than CONTENT_LENGTH bytes, even if more data is available. However,
it is not obliged to read any of the data.
The key line is:
the script MUST NOT attempt to read more
than CONTENT_LENGTH bytes, even if more data is available.
Apparently, apache sends an eof signal to the cgi script immediately after sending the request body to the cgi script, which causes sys.stdin.read() to return. But according to the cgi spec, a server is not required to send an eof signal after the body of the request, and I found that my cgi script was hanging on sys.stdin.read()--when my script was on another server, which eventually caused a timeout error.
Therefore, in order to read in json data in the general case, you should do this:
content_len = int(os.environ["CONTENT_LENGTH"])
req_body = sys.stdin.read(content_len)
my_dict = json.loads(req_body)
The server sets a bunch of environment variables for cgi scripts, which contain header information, one of which is CONTENT_LENGTH.
Here is what a failed curl request looked like when I used myjson = json.load(sys.stdin):
-v verbose output
-H specify one header
--data implicitly specifies a POST request
Note that curl automatically calculates a Content-Length header
for you.
~$ curl -v \
> -H 'Content-Type: application/json' \
> --data '{"a": 1, "b": 2}' \
> http://localhost:65451/cgi-bin/1.py
* Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 65451 failed: Connection refused
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 65451 (#0)
> POST /cgi-bin/1.py HTTP/1.1
> Host: localhost:65451
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 16
>
* upload completely sent off: 16 out of 16 bytes
=== hung here for about 5 seconds ====
< HTTP/1.1 504 Gateway Time-out
< Date: Thu, 08 Mar 2018 17:53:30 GMT
< Content-Type: text/html
< Server: inets/6.4.5
* no chunk, no close, no size. Assume close to signal end
<
* Closing connection 0
Adding a little bit to the great #7stud's answer
I had some problems with content length when reading unicode which I fixed by reading from buffer:
content_length = int(os.environ["CONTENT_LENGTH"])
data = sys.stdin.buffer.read(content_length).decode('utf-8')
I have problem with sending POST request to my rails application from Android app (using Spring for Android)
I have following Rails controller:
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email)
end
I'm sending POST request (using Spring for Android):
RestTemplate restTemplatePost = new RestTemplate();
restTemplatePost.getMessageConverters().add(new StringHttpMessageConverter());
UserDto user = new UserDto();
user.name = "testName";
user.email = "test#fromandroid.com";
Gson gson = new Gson();
String request = gson.toJson(user);
restTemplatePost.postForObject(createUserUrl, request, String.class);
} catch(RestClientException e) {
Log.e("POST",e.getLocalizedMessage());
}
value of String request is {"email":"test#fromandroid.com","name":"testName"}
and createUserUrl has value of: http://10.0.0.2:3000/users
however, I still get the following error:
> W/RestTemplate(3299): POST request for "http://10.0.0.2:3000/users"
> resulted in 400 (Bad Request); invoking error handler
I'm able to send the GET request, but POST doesn't work. What am I doing wrong?
I used CURL to get better error message and it returns:
param not found: user
so the problem might be with required user and optional name and emails parameters which are accepted by REST API, but how should I format user in json for it to work?
I'd greatly appreciate your help!
Please ensure that your controller config accept POST method, may be it just receives GET.
RailsController
RailsRouting
And you can use RestClient (Plugin of Firefox or Chrome) to test your api.
Rest Client - Firefox
Rest Client - Chrome
There are some issues you must have to follow to post.
you need to post data something like:
{"user_params" : {"email":"test#fromandroid.com","name":"testName"}}
to create a user (according to your controller).
To post data add Request Header. As you sending json data, so header will be Content-Type: application/json.
Also I'm suggesting you to use a FireFox addons is named "RESTClient" to simulate this scenario.
Thanks.