My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`
so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);
if (data ["success"] != null)
return (string)data ["success"];
throw new Exception ((string)data ["error"]);
}
and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));
if (!isset($users[0]))
return $this->_response(array("error" => "User not found"), 403);
$user = $users[0];
if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
$user->user_token = $token;
$u_dao->update($user);
return $this->_response(array("success" => $token));
}
return $this->_response(array("error" => "Bad login"), 403);
}
return $this->_response(array("error" => "Missing data"), 500);
}
return $this->_response(array("error" => "Wrong method"), 405);
}
and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}
and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}
and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"
and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"
i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".
Related
I have used dialogflow fulfillment to get data from an external api. It works fine with the test console. But on being deployed on to an android app, it gives a blank response. How do I fix this? Thanks.
The code in fulfillment:
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function rhymingWordHandler(agent){
const word = agent.parameters.word;
agent.add(`Here are the rhyming words for ${word}`);
return axios.get(`https://api.datamuse.com/words?rel_rhy=${word}`)
.then((result) => {
result.data.map(wordObj => {
agent.add(wordObj.word);
});
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Rhyme Scheme', rhymingWordHandler);
agent.handleRequest(intentMap);
});
The code in MainActivity.java
public void callback(AIResponse aiResponse) {
if (aiResponse != null) {
// process aiResponse here
String botReply = aiResponse.getResult().getFulfillment().getSpeech();
Log.d(TAG, "Bot Reply: " + botReply);
showTextView(botReply, BOT);
} else {
Log.d(TAG, "Bot Reply: Null");
showTextView("There was some communication issue. Please Try again!", BOT);
}
}
Hi I'm newbie in android!
I want to upload image file from android client to server(Server makes thumbnail, and return thumbnail's url).
However I stucked in this error message.
{"errorMessage":"RequestId: 8e2a21b8-e62e-11e8-8585-d9b6fdfec9b9 Process exited before completing request"}!
I tried to find this error code in stackoverflow, but i cannot found answer for android.
Please help or give me link where I can solve this problem...
Here is server code.
const AWS = require('aws-sdk');
const multipart = require("parse-multipart");
const s3 = new AWS.S3();
const bluebird = require('bluebird');
exports.handler = function(event, context) {
let result = [];
const bodyBuffer = new Buffer(event['body-json'].toString(), 'base64');
const boundary = multipart.getBoundary(event.params.header['Content-Type']);
const parts = multipart.Parse(bodyBuffer, boundary);
const files = getFiles(parts);
return bluebird.map(files, file => {
console.log('UploadCall');
return upload(file)
.then(
data => {
result.push({
'bucket': data.Bucket,
'key': data.key,
'fileUrl': file.uploadFile.fullPath })
console.log( `DATA => ${JSON.stringify(data, null, 2 )}`);
},
err => {
console.log(`S3 UPLOAD ERR => ${err}`);
}
)
})
.then(_=> {
return context.succeed(result);
});
}
let upload = function(file) {
console.log('PutObject Call')
return s3.upload(file.params).promise();
};
let getFiles = function(parts) {
let files = [];
parts.forEach(part => {
const buffer = part.data
const fileName = part.filename;
const fileFullName = fileName;
const originBucket = 'dna-edge/images';
const filefullPath = `https://s3.ap-northeast-2.amazonaws.com/${originBucket}/${fileFullName}`;
const params = {
Bucket: originBucket,
Key: fileFullName,
Body: buffer
};
const uploadFile = {
size: buffer.toString('ascii').length,
type: part.type,
name: fileName,
fullPath: filefullPath
};
files.push({ params, uploadFile })
});
return files;
};
And this is client code.(imgURL looks like /storage/emulated/0/DCIM/img/1493742568136.jpg)
public static String requestHttpPostLambda(String url, String imgURL){
/*
await axios.post(`${AWS_LAMBDA_API_URL}?type=${type}`, formData,
{ headers: { 'Content-Type': 'multipart/form-data' }})
.then((response) => {result = response});
*/
String result=null;
try {
HttpClient client = new DefaultHttpClient();
String postURL = url;
HttpPost post = new HttpPost(postURL);
post.setHeader("Content-Type", "multipart/form-data");
File file = new File(imgURL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("image", new FileBody(file));
post.setEntity(builder.build());
HttpResponse responsePOST = client.execute(post);
Log.e("HttpResponse", responsePOST.getStatusLine()+"");
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Welcome to stackoverflow.
So for some reason AWS aren't too good an updating the docs, don't use context.succeed, use the callback thats passed as a third param.
Also I'd move to Node 8.10 runtime because then rather than using promises/then pattern you can use async/await.
export default(event, context, callback) => {
try {
// do some stuff
callback(null, SOME_VALID_HTTP_RESPONSE)
} catch(e){
callback(e, null)
}
}
There's a few reason your Lambda could be failing, if the process exited before completing it's either crashing OR you're not returning a valid HTTP response(if your lambda is behind API gateway)
Two solutions - first place to look is in cloudwatch, find your lambda function name and check the latest log to look for error messages.
Second - check out my answer here so when your function succeeds you need to return a valid HTTP response to API Gateway so in essence if you use my code from there you can do:
callback(null, responder.success({someJson: someValue}))
Any questions let me know :-)
EDIT: I'm updating this question I'm just working on an example for a multiple file upload to S3!
I have a link in the back-end, so I fetch a post request to that link and receive a response. When I alert that response it gives a body init and body text in which I receive datas I need. Everything is good. But..
When I enable remote debugging and console.log that response, it gives body init and body blob (and both are empty). It stucks when I eneble debugging..
Thanks for attention ))
My code:
logIn = async (username, password) => {
// alert(`username : ${username}\n password : ${password}`);
let loginFormData = new FormData();
loginFormData.append('LoginForm[username]', username);
loginFormData.append('LoginForm[password]', password);
loginFormData.append('MacAddress', '111');
loginFormData.append('loginType', 'mobile');
try {
fetch('http://192.168.2.115/araqich_client/general/default/logout', {
method: 'POST',
body: loginFormData
});
let request = fetch('http://192.168.2.115/araqich_client/general/default/login', {
method: 'POST',
body: loginFormData
});
let loginResponseJson = await request;
if (loginResponseJson && loginResponseJson != null ) {
// let loginResponse = JSON.parse(loginResponseJson._bodyInit);
alert(JSON.stringify(loginResponseJson._bodyInit));
let status = loginResponse.status;
if (status) {
let SyncFormData = new FormData();
let accessToken = loginResponse.ACCESS_TOKEN;
SyncFormData.append('ACCESS_TOKEN', accessToken);
SyncFormData.append('MacAddress', '111');
SyncFormData.append('loginType', 'mobile');
let syncRequest = fetch('http://192.168.2.115/araqich_client/mobile/defaultA/syncAndroid', {
method: 'POST',
body: SyncFormData
});
let syncResponseJson = await syncRequest;
if (syncResponseJson && syncResponseJson != null) {
let syncResponse = JSON.parse(syncResponseJson._bodyInit);
let status = syncResponse.status;
if (!status) {
alert('Sorry(( something went wrong...');
} else {
alert('Life is good)))');
}
}
} else {
alert('else1')
}
} else {
alert('else')
}
} catch (error) {
alert(error);
}
}
Instead of using console.log statements, I'd advise using your debugger.
i am sending ajax request to server to get the database. But if i enter incorrect data (which is to be sent over server) nothing is happening, error function is not working, all i am doing is to verify credentials from the server
here is my code
$.ajax
({
url: "URL",
type: "GET",
datatype: "jsonp",
data: {type: 'login', id: C_id},
ContentType: "application/json",
success: function(res)
{
var simpleJson = JSON.parse(res);
myDB.transaction(function (txe1)
{
for (var i = 0; i < simpleJson.User.length; i++)
{
var Cli_id= simpleJson.User[i].id;
myDB.transaction(function (txe)
{
txe.executeSql('CREATE TABLE Client_data(Mobile integer , C_id integer, U_id integer , name text , ip integer )');
});
myDB.transaction(function (txe1)
{
var data_ins = 'INSERT INTO Client_data (Mobile,C_id,U_id) VALUES (?,?,?)';
txe1.executeSql(data_ins, [p,C_id,U_id]
,function(tx, result)
{
navigator.notification.alert('Inserted' , onSignup, 'Info', 'ok');
},
function(error)
{
navigator.notification.alert('Already Registered');
});
});
}
});
},
});
});
my PHP code
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes));
echo $output;
}
else
{
print "invalid key";
}
}
else
{
print "invalid login";
}
}
else
{
echo "invalid";
}
mysql_close();
?>
You should implement the error callback to perform some operation when the request fails. This is how you can implement request failure callback.
$.ajax({
url: "/save/author",
type: "POST",
dataType: "json",
data: { name: "John", age: "35" },
success: function (data, status, jqXHR) {
alert("request succeed");
},
error: function (jqXHR, status, err) {
alert("request failed");
}
})
as per this example, we are just showing an alert with text request failed. You can implement it accordingly as per your requirement.
If i get you correct,you want to validate the data passed to your url, if i am getting you correct you want to handle,please refer below:
Ajax error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return any response from your PHP server/API, the error function won't be triggered as The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
However, you can return a key from your PHP code as below to handle success and error in your ajax code:
$data['error'] = $success ? 0:1;// If success than set error to 0 else 1;
and in AJAX success you can handle it as :
success: function (data, status, jqXHR) {
if(data.error)
//do something
else
//do something else
}
Let me know if any queries
------EDIT------------------
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$is_error=0;
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes,'is_error'=>$is_error));
echo $output;
}
else
{
$is_error=1;
$error_message = "Invalid Key";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid Login";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
mysql_close();
?>
In AJAX Code access it like this :
Check for following in success
if(simpleJson.is_error!=1)
//do your processing
else
alert(simpleJson.error_message);
Let me know if anything unclear
I try to develop my new app with Ionic2. In this context, the user should be authenticated with a pre shared token which will be sent to the api (http request). As a response he get an access token with which he can use further api functions.
The problem is that when I send an HTTP request, I get as an error:
{"_body":{"isTrusted":true},"status":200,"statusText":"Ok","headers":{},"type":3,"url":null}
In my desktop version everything works fine, but on Android I get this error. I still googled this error and I guess that the http request comes in conflict with other observables (Form observable).
I would be very pleased if someone could help me to avoid this "error".
As a small hint: {"isTrusted":true} is the value of the event value of the method handleSubmit. Thank you :-)
Solution:
This error was thrown because the api was not reachable (in my case due to a certificate error). When you have the same error:
Check if type="3", then it is possible that your http target is also not reachable.
My template:
<ion-content padding class="token-auth">
<form [ngFormModel]="authForm" (submit)="handleSubmit($event)">
<ion-item>
<ion-label floating>Device-ID</ion-label>
<ion-input (keyup)="onKeyUp($event)" [ngFormControl]="token" type="text"></ion-input>
</ion-item>
<div *ngIf="error !== null"
class="error-box">
{{error.message}}
</div>
<button block type="submit" [disabled]="!authForm.valid">
Register device
</button>
</form>
</ion-content>
Page source:
handleSubmit(event) : void {
this.tokenService.sendAccessTokenRequest(this.authForm.value.token, (err, code) => {
this.error = {
code : code,
message : err
};
}, (accessToken, refreshToken, validTill) => {
this.error = null;
});
}
TokenService:
/**
*
* #param token
* #param errCallback : (message : string, code : number) => any
* #param callback : (accessToken : string, refreshToken : string, validTill : string) => any
*/
public sendAccessTokenRequest(token : string, errCallback, callback) {
if (typeof token === 'undefined') {
throw 'Token value must be set. ';
}
if (typeof errCallback === 'undefined') {
errCallback = (code, message) => null;
}
if (typeof callback === 'undefined') {
callback = (accessToken, refreshToken, validTill) => null;
}
console.log(`Should send token: ${token}`);
this.sendPost(`/auth/login`, `application=XXX&device_token=${token}`)
.subscribe(res => {
console.log("Device verified: "+JSON.stringify(res));
let {
access_token,
refresh_token,
valid_till
} = res.data.token;
this._saveTokenData(access_token, refresh_token, new Date(valid_till));
callback(access_token, refresh_token, valid_till);
},
err => {
// error is here!
if (err && err._body) {
console.log("ERROR: "+JSON.stringify(err));
try {
let bodyData = JSON.parse(err._body);
let responseData = bodyData["data"];
let token:MessageResponse = responseData.token;
if (token && typeof token.code !== 'undefined' && typeof token.userMessage !== 'undefined') {
errCallback(token.userMessage, token.code);
} else {
errCallback(bodyData);
}
} catch (e) {
errCallback(e);
}
}
},
() => console.log("access token request successful")
);
}
// just an excerpt from other url
sendPost(link : string, params : string, header : Object = {}) {
console.log("SEND POST");
link = this._enforceSlashAtStringStart(link);
return this.http.post(`${this.base_url}${link}`, params, {
headers : this._mergeHeader(this.getHeader(), header)
}).map(res => { console.log("Start mapping! "); return res.json(); });
}
// EDIT: added function _saveTokenData
private _saveTokenData(accessToken : string, refreshToken : string, validTill : Date) {
if (!accessToken || !refreshToken || !validTill) {
throw new Error('access token data can not be null or undefined! ');
}
console.log("TOKEN SAVED!");
this._accessToken = accessToken;
this._refreshToken = refreshToken;
this._validTill = validTill;
// this._storage = new Storage(LocalStorage);
this._storage.set(TOKEN_STORAGE_KEY, JSON.stringify({
access_token : accessToken,
refresh_token : refreshToken,
valid_till : validTill.toString()
}));
}
And last but not least the logs:
14 256534 log Should send token: XXXXXXXXXXXXXX
15 256548 log SEND POST
16 256750 log ERROR: {"_body":{"isTrusted":true},"status":200,"statusText":"Ok","headers":{},"type":3,"url":null}
Remove the webkit plugin from ios project and it will start working.