My Retrofit should recieve a List of Bookmarks, and everything worked while I was using WAMP server. When I changed server to external (nothing else changed, just ip address of the server and retrieving of everything else works) I have an error:
java.io.EOFException: End of input at line 1 column 1
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1407)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:553)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:74)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:116)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
My Retrofit code:
public void init() {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor debugger =
new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient
.addInterceptor(debugger);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient.build())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
String email = pref.getString(Constants.EMAIL, "");
System.out.println(email);
String id_group = pref.getString(Constants.ID_GROUP, "");
System.out.println(id_group);
String nazwa = pref.getString(Constants.NAZWA, "");
Integer id_int_group = Integer.parseInt(id_group);
Bookmark bookmark = new Bookmark(email, id_int_group, nazwa);
ServerRequest request2 = new ServerRequest();
request2.setOperation(Constants.GET_MY_GROUPS);
request2.setBookmark(bookmark);
Call<List<Bookmark>> response2 = requestInterface.operation2(request2);
response2.enqueue(new Callback<List<Bookmark>>() {
#Override
public void onResponse(Call<List<Bookmark>> call, retrofit2.Response<List<Bookmark>> response2) {
listOfBookmarks = response2.body();
bookmarkToString();
simpleAdapter.notifyDataSetChanged(); // refresh listivew
}
#Override
public void onFailure(Call<List<Bookmark>> call, Throwable t) {
Log.d(Constants.TAG, "Nie zaladowano!", t);
}
});
}
EDIT://
PHP code:
<?php
class Bookmark {
private $host = 'localhost';
private $user = 'nwbrn_root';
private $db = 'nwbrn_app';
private $pass = 'zxs#1208NMLK';
private $conn;
public function __construct() {
$this -> conn = new PDO("mysql:host=".$this -> host.";dbname=".$this -> db, $this -> user, $this -> pass);
}
public function checkBookmarkExist($email, $id_group){
try {
$query = $this->conn->prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group");
// $query = $this -> conn -> prepare($sql);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->execute(array('email' => $email, 'id_group' => $id_group));
$row_count = $query -> fetchColumn();
if ( $row_count>0 ) {
$response["result"] = "success";
$response["message"] = "Your favourite!";
return json_encode($response);
}
else {
$response["result"] = "failure";
$response["message"] = "Not in your favourite!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function fullStarSelected($email, $id_group, $nazwa){
try {
$query = $this->conn->prepare("DELETE from bookmarks WHERE email =:email AND id_group =:id_group AND nazwa =:nazwa");
// mysqli_set_charset($this->conn, "utf8");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->bindParam(':nazwa', $nazwa, PDO::PARAM_STR);
$query->execute();
if ( $query ->rowCount() > 0 ) {
$response["result"] = "failure";
$response["message"] = "Row not deleted!";
return json_encode($response);
}
else {
$response["result"] = "success";
$response["message"] = "Row deleted successfully!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function blankStarSelected($email, $id_group, $nazwa){
try {
$query = $this->conn->prepare("INSERT INTO bookmarks (email, id_group, nazwa) VALUES (:email, :id_group, :nazwa)");
// mysqli_set_charset($this->conn, "utf8");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->bindParam(':nazwa', $nazwa, PDO::PARAM_STR);
$query->execute();
if (!$query) {
printf("Error: %s\n", mysqli_error($this->conn));
exit();
}
$result = array();
// $query1 = $this->conn->prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group LIMIT 1");
if ( $query->rowCount() > 0 ) {
$response["result"] = "success";
$response["message"] = "Row added successfully!";
return json_encode($response);
}
else {
$response["result"] = "failure";
$response["message"] = "Row not added!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function getMyGroups($email, $id_group){
try {
$con = mysqli_connect($this->host,$this->user,$this->pass,$this->db);
$sql = "SELECT * FROM bookmarks WHERE email = '$email'";
$res = mysqli_query($con,$sql);
$result = array();
if (!$res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
while($row = mysqli_fetch_array($res)){
$temp = array();
$temp['id_group']=$row['id_group'];
$temp['email']=$row['email'];
$temp['nazwa']=$row['nazwa'];
array_push($result,$temp);
}
echo json_encode($result);
} catch (PDOException $e) {
die ($e->getMessage());
}
}
}
When you see
java.io.EOFException: End of input at line 1 column 1
it indicates a problem with parsing something. It's expecting some text to parse but it got End of File (EOF).
Then you said:
When I changed server to external (nothing else changed)
If this worked before, your problem is definitely not on your code and it is on the data you're retrieving. Your new server is either rejecting your requests or returning blank data. Try doing the same request manually (via postman or some other api client) and see what the response is. It'll very likely tell you where the error is.
I had this error because the body of the answer was passing an empty text "", I solved it by passing it a body null since certain methods that depend on the value of the body are being used. And when having an empty value, the necessary check-ups are not made, instead with the null value of the body, the flow is conditioned by the nullity.
In the declaration I went on to define a null value by default fun response(httpCode: Int, body: String? = null): Response<T>
In the invocation I went from Request#response(200, "") to Request#response(200)
According to the http code protocol, only 204 can allow the body to be null although this may vary depending on the particular service of the needs of one.
GL
Related
BackEnd create route generate WSDL file using zend soap of Zendframework in laravel 7
if(isset($_GET['wsdl'])) {
// Create wsdl object and register type(s).
$wsdl = new Wsdl('wsdl', $this->endpoint);
foreach($this->types as $key => $class) {
$wsdl->addType($class, $key);
}
// Set type(s) on strategy object.
$this->strategy->setContext($wsdl);
foreach($this->types as $key => $class) {
$this->strategy->addComplexType($class);
}
// Auto-discover and output xml.
$discover = new AutoDiscover($this->strategy);
$discover->setBindingStyle(array('style' => 'document'));
$discover->setOperationBodyStyle(array('use' => 'literal'));
$discover->setClass($this->service);
$discover->setUri($this->endpoint);
$discover->setServiceName($this->name);
echo $discover->toXml();
} else {
$server = new Server($this->endpoint . '?wsdl');
// $server = new SoapServer($this->endpoint . '?wsdl', array(
// 'style' => SOAP_DOCUMENT,
// 'use' => SOAP_LITERAL,
// ));
// $server->setObject(new DocumentLiteralWrapped(new $this->service()));
// $server->handle();
$server->setClass(new DocumentLiteralWrapper(new $this->service()));
$server->registerFaultException($this->exceptions);
$server->setOptions($this->options);
// Intercept response, then decide what to do with it.
$server->setReturnResponse(true);
$response = $server->handle();
// Deal with a thrown exception that was converted into a SoapFault.
// SoapFault thrown directly in a service class bypasses this code.
if ($response instanceof SoapFault) {
$output->headers->set("Status", 500);
return self::serverFault($response);
} else {
return $response;
// echo $response;
}
}
laravel route generate wsdl use that in laravel for create soap client but it give fail tot load wsdl and when we use for Mobile app it return exception "HTTP request failed, HTTP status: 500"
Generate WSDL tag order using zend soap (same as zoap code)
<types> </types>
<portType> </portType>
<service> </service>
<message> </message>
it give soap action with #method name we use that for mobile
** Mobile App Code**
private val NAMESPACE = "http://10.2.0.114:8001/api/server/account-action";
private val METHODNAME = "withdrawDetail"
private val WSDL = "http://10.2.0.114:8001/api/server/account-action?wsdl";
private val SOAP_ACTION = "$NAMESPACE#$METHODNAME"
private val TAG = "soap"
var responseDump = ""
try {
val envelope = SoapSerializationEnvelope(SoapEnvelope.VER11)
val request = SoapObject(NAMESPACE, METHODNAME)
request.addProperty("withdrawId", "1")
request.addProperty("token", "695E8784AE45B219F62C4EBE21E3E")
val headerList: MutableList = ArrayList()
headerList.add(HeaderProperty("Content-Type", "application/xml; charset=UTF-8"))
headerList.add(
HeaderProperty(
"Authorization",
"Bearer " + "695E8784AE45B219F62C4EBE21E3E"
)
)
headerList.add(
HeaderProperty(
"Content-Type", "application/xml"
)
)
headerList.add(HeaderProperty("soapAction", NAMESPACE))
envelope.bodyOut = request
val transport = HttpTransportSE(WSDL)
transport.debug = true
try {
transport.call(SOAP_ACTION, envelope, headerList)
val requestDump = transport.requestDump
responseDump = transport.responseDump
Log.e(TAG, responseDump)
} catch (e: IOException) {
e.printStackTrace()
}
} catch (e: Exception) {
e.printStackTrace()
}
return responseDump
}
This is my php file :
I want to Insert data into detaildonasi based on last id in donasi table
<?php
$conn = new mysqli("localhost","root","","donasiku");
$sql = "SELECT * FROM donasi ORDER BY id DESC LIMIT = 1";
$result = $conn->query($sql);
if($result === TRUE)
{
$id = $result->fetch_assoc();
$jumlah = $_POST['jumlah'];
$kebutuhanid = $_POST['kebutuhanid'];
$sql2 = "INSERT INTO detaildonasi VALUES('','$jumlah','$id','$kebutuhanid')"
$result2 = $conn->query($sql2);
if($result2 === TRUE)
{
$arr = array('hasil' => 'success');
}
else
{
$arr = array('hasil' => $conn->error);
}
}
else
{
$arr = array('hasil' => $conn->error);
}
echo json_encode($arr);
$conn->close();
?>
This is the Volley of my Fragment file :
val q2 = Volley.newRequestQueue(this.context)
val url2 = "http://10.0.2.2/donasiku/detaildonasi.php"
val sr2 = object:StringRequest(Request.Method.POST,url2,Response.Listener {
response -> try{
val obj2 = JSONObject(response)
Toast.makeText(this.context,obj2.getString("hasil"), Toast.LENGTH_SHORT).show()
}catch (e:JSONException){Toast.makeText(this.context, e.message.toString(), Toast.LENGTH_SHORT).show()}
},Response.ErrorListener { })
{
override fun getParams(): Map<String, String> {
val params2 = HashMap<String, String>()
for(donasi in daftarDonasiUser)
{
params2.put("jumlah",donasi.jumlahbarang.toString())
params2.put("kebutuhanid",donasi.idbarang.toString())
}
return params2
}
}
q2.add(sr2)
The code goes into catch JSONException and Toast Value br of type java.lang.String cannot be converted to JSONObject.
<br is html. Your api is erroring in some way and so html of some kind (instead of the Json you are expecting) is being written to the page.Try making the same request in Postman and viewing the response.
"Server Error" in nodejs api (android to web server request)
I am a new node.js learner. I'm doing a project that user are registration by android application, and user details will go to web server. but when i send request to web server by API that time show "Server Error Problem". but when i send data by (postman row data) that time it works, but if i send by (postman form-data) that time it not work, and show "Server Error Problem".
In addition, I am using a shared linux Server supported by cpanel and CloudLinux.
-----------------------
index.js file
------------------------
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const verifyToken = require('./jwt/verify/verifytoken');
const mysql = require('mysql');
global.config = require('./jwt/config/config');
const extInfo = require('./info/extInfo');
const port = process.env.PORT || 3000;
const connection = mysql.createConnection({
host: "localhost",
user: “abcd”,
password: "123345",
database: “xyz”
});
var point = 0;
const app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(express.json());
app.use(bodyParser.urlencoded({extended : false}));
app.use(cors());
app.use('/api/v1', require('./api/v1'));
------------------------------------
api file (code)
---------------------------
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
var error = ["error", "error", "error"];
const connection = mysql.createConnection({
host: "localhost",
user: “abcd”,
password: “12345”,
database: “xyz”
});
router.get('/login?', (req , res) => {
var studentdata = {
A: req.query.a,
B: req.query.b
}
connection.query(`Select Student_id from student where Mobile = ${a} and Password = ${b}`, (err, result, fields) => {
if (err) {
console.log("error");
res.send(error);
} else if (result.length < 1){
console.log("error");
res.send(err);
}
return res.send(result);
let Student_id = result[0].Student_id ;
connection.query(`SELECT * FROM B where A = ${A}`, (err1, result1, fields1) => {
if(err1){
res.send(err1);
} else if (result1.length < 1){
res.send(error);
}
res.send(result1);
});
});
});
router.post('/registration', (req , res) => {
let newStudent = {
a : req.body['a'],
b: req.body.b,
....
c: req.body.c
}
connection.query(`SELECT * FROM d1 where Mobile = ${a}`, (err, result , fields) => {
if(err) {
return res.send("Server Error");
} else if (result.length > 0) {
return res.send("wrong phone");
}
connection.query(`INSERT INTO d1 (Student_name, School , ..... , Password ) VALUES ('${newStudent.student_name}', ..... , '${newStudent.student_password}')`, (err1, result1, fields1) => {
if(err1) {
return res.send(error);
} else if (result1.length > 0) {
return res.send("wrong phone");
}
let insertId = result1.insertId;
// Create Score table Account
connection.query(`INSERT INTO d2( A ) VALUES ('${insertId}')`, (err2, result2, fields) => {
if (err2) {
return res.send(err2);
}
return res.send("Registration Successful");
});
})
});
});
router.get('*', (req , res) => {
res.send({"info" : "Nothing Found"});
});
module.exports = router ;
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
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".