Hi where to convert a json using node.js, to do it using body-parser with the code entered below: I am generated the error below. What is this error due to? how can I solve it? At the bottom I added the front-end java code for sending the json! The strange thing is that the -Note- field is not displayed in the request.body
Error --> console.log(request.body):
'{"Articoli":':
{ '{"Codice":"VAS-100","Descrizione":"SCHEDA DI ANALISI AD 1 INGRESSO \/ 1 USCITA ALLARME","Prezzo":"35.0"}': '' } }
Error SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
Node.js:
const express = require("express");
const myParser = require("body-parser");
const http = require('http');
const app = express();
app.use(myParser.json());
app.use(myParser.urlencoded({ extended: true }));
//port
const RunPort=8989;
//server run on port
app.listen(RunPort, function () {
console.log("Server run on Port: ",RunPort);
})
app.post("/rapportini/generarapportino", async function (request, response) {
try {
console.log(request.body);
var data = JSON.parse(Object.keys(request.body)[0]);
const ret = await RapportiniController.GeneraRapportino(data.Note);
response.setHeader('Content-Type', 'application/json');
response.send(JSON.stringify({
return: ret
}));
} catch (err) {
console.log("Error ", err)
}
});
JSON:
{
"Note": "some note",
"Articoli":[{
"Codice": "CodiceValue 1",
"Descrizione": "DescrizioneValue 1",
"Presso": "Prezzo 1"
},
{
"Codice": "CodiceValue 2",
"Descrizione": "DescrizioneValue 2",
"Presso": "Prezzo 2"
}]
}
Front-End Java Code(Android):
Generate JSON:
String ret = "";
try {
JSONObject obj = new JSONObject();
obj.put("Note", note);
JSONArray objarticoli = new JSONArray();
int size = articoli.size();
int i = 0;
System.out.println("\n Size of articoli: " + size);
for (i = 0; i <
size; i++) {
JSONObject artItem = new JSONObject();
artItem.put("Codice", articoli.get(i).GetCodice().toString());
artItem.put("Descrizione", articoli.get(i).GetDescrizione().toString());
artItem.put("Prezzo", articoli.get(i).GetPrezzo().toString());
objarticoli.put(artItem);
}
obj.put("Articoli", objarticoli);
try {
Database db = new Database();
ret = db.RequestArray("/rapportini/generarapportino", obj, true);
} catch (Exception ex) {
System.out.println("\n Errore login Model");
}
} catch (Exception ex) {
ErrorManagement.SendError("Errore: Generazione Rapportino: " + ex);
}
return ret;
Send of JSON:
String response = "";
System.out.println("\n Sono in GetResponse con JSONOject: "+object);
try {
URL url = new URL("/rapportini/generarapportino");
byte[] postDataBytes = object.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; ) {
sb.append((char) c);
}
response = sb.toString();
} catch (Exception ex) {
System.out.println("\n Errore funzione GetResponse class JSONRequest: "+ex);
}
return response;
First Use JSON.stringify then parse it to get desired output
var req={ '{"Articoli":': { '{"Codice":"KSI4101000.300","Descrizione":"gemino Bus Scheda GSM\/GPRS (solo PCBA) solo per KS-BUS","Prezzo":"163.35"}': '' } }
var data = JSON.parse(JSON.stringify(req));
You need to set correct Content-Type in Android application that is application/json
conn.setRequestProperty("Content-Type", "application/json");
and then accept in NodeJS application
app.post("/rapportini/generarapportino", async function (request, response) {
try {
const ret = await RapportiniController.GeneraRapportino(request.body.Note);
response.json({
return: ret
});
} catch (err) {
console.log("Error ", err)
}
});
Related
I am trying to make api call every 60 mins which returns json response like below:
[{
"queryId" : uniqueID,
"state": "FINISHED | FAILED | RUNNING"
},
{
"queryId" : uniqueID,
"state": "FINISHED | FAILED | RUNNING"
},
]
I want to run first time and prepare each document and store and for the next api call i want to compare current response with previous response with below condition:
1: if same queryId exit in previous response and state as FINISHED | FAILED don't consider to store.
So idea is to get every 60 secs new queryID which is running in system and store it for further analysis.
Below is my sample snipeet:
#Override
public void run() {
stopRequested = false;
while (!stopRequested)
{
try {
System.setProperty("javax.net.ssl.trustStore","");
System.setProperty("javax.net.ssl.trustStorePassword","");
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("", "".toCharArray());
}
});
URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " + responsecode);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
JSONArray array = new JSONArray(response.toString());
System.out.println(array.length());
JSONArray presResponse = array;
for(int i=0; i < array.length(); i++)
{
JSONObject object = array.getJSONObject(i);
// Query
String queryId = object.getString("queryId");
String state = object.getString("state");
if (checkQryExit(queryId, state, presResponse)) {
String strResponse = String.format // metric return in json
("{\"queryId\":\"%s\"," + "\"state\":\"%s\"}", queryId, state);
System.out.println(strResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I have an Android app, and I send a Http request via getJson() method to get a generated JSON file from the web server. However, the result I always get in my Android app looks like this (looks like HTML, not like a JSON object):
I/System.out: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("674bdf26f9a5fe3df1461aafc3120641");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://example.net/index.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
index.php
<?php
$results = array(
"result" => "success",
"username" => "some username",
"projects" => "some other value"
);
header('Content-type: application/json');
echo json_encode($results);
?>
Connection method:
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
Call:
String data = getJSON("http://example.net", 10000);
// or String data = getJSON("http://example.net/index.php", 10000);
System.out.println(data);
The "example.net" URL is a valid URL, where it shows correctly the JSON file when opened in the browser.
Question: How do I obtain JSON file in an Android app, when Android's HttpURLConnection doesn't support JavaScript?
I try to get a JSON from my server that should echo json_encode me a variable and return a JSON that looks like below. However, everytime I try to debug the code, I got null on builder. I tried to use a .json file that stocks only data in JSON format and it worked. So , I don't understand why my code doesn't work. Is there any problem with my code? Thank you in advance.
{
"id":"714184",
"corpid":"52233",
"staffMail":"",
"smartTags":[],
"formatted_createdDate":"07/02/2018",
"thirdcontactid":"11210400",
"customfields":[
{
"id":0,
"status":"ok",
"formattedVal":""
},
{
"id":2,
"status":"ok",
"formattedVal":""
}
]
}
Java code where I used Asynctask method to connect to my server
public class PHPConnecteur extends AsyncTask<String, Integer, String>{
private HashMap<String, String> parameters;
private String phpToCall;
public PHPConnecteur(HashMap<String, String> params, String phpTC){
phpToCall = phpTC;
parameters = params;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
//System.setProperty("http.keepAlive", "false");
String dataParsed = "";
try {
String u = "https://api.asii.fr/api/".concat(phpToCall);
URL url = new URL(u);
JSONObject postDataParams = new JSONObject();
Iterator<HashMap.Entry<String, String>> entries = parameters.entrySet().iterator();
while (entries.hasNext()) {
HashMap.Entry<String, String> entry = entries.next();
postDataParams.put(entry.getKey(), entry.getValue());
}
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (parameters.size() > 1){ // si ce n'est pas la liste d'incident
conn.setReadTimeout(15000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
}else{
conn.setReadTimeout(15000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
}
InputStream stream = new BufferedInputStream(conn.getInputStream());//here is where i should get the output from php
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuffer builder = new StringBuffer();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);// gives me null when debug
}
/*JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("id");
dataParsed = String.valueOf(main.getDouble("temp"));*/
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return dataParsed;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(final String result) {
//delegate.onTaskCompleted(result);
}
}
You should add "Content-Type:" header in your PHP script.
$data = [];
header('Content-Type: application/json');
echo json_encode($data);
I found the solution. Actually, the JSON i get from my PHP is in the correct format but it just doesn't have a line break. So what I did in my PHP is, I added a JSON_PRETTY_PRINT when echoing the JSON. That's all, problem solved.
echo json_encode($data, JSON_PRETTY_PRINT);
PHP code:
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
# Request id value that is sent from android
$id=$_REQUEST['id'];
$r=mysql_query("select * from sample where id='$id'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
?>
Then android side code:
public void select() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
// add whatever you would like to parse (all values you are
// sending from PHP)
name = (json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : " + name,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
Source: http://sampleprogramz.com/android/mysqldb.php
Hope this helps! Good luck!
In the given below Class i am trying to write an JSON object into the Given HttpURL connection. But it when i try to run my class it givin me some values which i have printed but ending with an error. When i debug it in each JSON object it is getting values and at Last i have put all the JSON object into one JSON object then try to write to url but end with the following error
The main class is given below where i have written code to get my System information.here i want to get System information and then want to send that information to an url, so that it can be get from that URL. But after getting values it ends with an error.
public class NetClientPost {
public static void main(String[] args) {
try {
URL url = new URL(
"http://projects.kpmpjdc.org/artist/artist_api/test");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
}
// try
System.out.println(method.getName() + " = " + value);
obj1.put(method.getName(), value);
}}
FileSystemView filesystemBean = FileSystemView.getFileSystemView();
File[] roots = filesystemBean.getRoots();
JSONObject obj2 = new JSONObject();
obj2.put("Roots", roots[0]);
filesystemBean.getHomeDirectory();
obj2.put("HomeDirectory", filesystemBean.getHomeDirectory());
File[] f = File.listRoots();
obj.put("RD", obj2);
for (int i = 0; i<f.length; i++)
{
JSONObject temp = new JSONObject();
temp.put("Drive", f[i]);
temp.put("Display name", filesystemBean.getSystemDisplayName(f[i]));
temp.put("Is drive", filesystemBean.isDrive(f[i]));
temp.put("Is floppy", filesystemBean.isFloppyDrive(f[i]));
temp.put("Readable", f[i].canRead());
temp.put("Writable", f[i].canWrite());
temp.put("Total Space", f[i].getTotalSpace());
temp.put("Space Use", f[i].getFreeSpace());
temp.put("Space Free", f[i].getUsableSpace());
obj.put("TEMP", temp);
}
obj.put("SystemInfo1", obj1);
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
os.write(obj.toString());
System.out.println(obj.toString());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The Error comes after running it is
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 200
at com.wiesoftware.rest.client.NetClientPost.main(NetClientPost.java:142)
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
you manually throw exception here when you reply code is 200, which means absolute success. Remove that line and should work
I am attempting to send a user update to valance and I am looking for an example of how to do a put, specifically, a put to update a user.
I have looked around but do not see an example of how to use the UserContext to send a json block using Java.
Any pointers to documentation would be appreciated.
After tinkering with this, and with a great number of suggestions from my colleague (Who I am not sure wants to be identified so i will just call him Bill). We came up with the following Java method(should really be split into separate methods but it is understandable)
private static String getValanceResult(ID2LUserContext userContext,
URI uri, String query, String sPost, String sMethod, int attempts) {
String sError = "Error: An Unknown Error has occurred";
if (sMethod == null) {
sMethod = "GET";
}
URLConnection connection;
try {
URL f = new URL(uri.toString() + query);
//connection = uri.toURL().openConnection();
connection = f.openConnection();
} catch (NullPointerException e) {
return "Error: Must Authenticate";
} catch (MalformedURLException e) {
return "Error: " + e.getMessage();
} catch (IOException e) {
return "Error: " + e.getMessage();
}
StringBuilder sb = new StringBuilder();
try {
// cast the connection to a HttpURLConnection so we can examin the
// status code
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod(sMethod);
httpConnection.setConnectTimeout(20000);
httpConnection.setReadTimeout(20000);
httpConnection.setUseCaches(false);
httpConnection.setDefaultUseCaches(false);
httpConnection.setDoOutput(true);
if (!"".equals(sPost)) {
//setup connection
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json");
//execute connection and send xml to server
OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream());
writer.write(sPost);
writer.flush();
writer.close();
}
BufferedReader in;
// if the status code is success then the body is read from the
// input stream
if (httpConnection.getResponseCode() == 200) {
in = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
// otherwise the body is read from the output stream
} else {
in = new BufferedReader(new InputStreamReader(
httpConnection.getErrorStream()));
}
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
// Determine the result of the rest call and automatically adjusts
// the user context in case the timestamp was invalid
int result = userContext.interpretResult(
httpConnection.getResponseCode(), sb.toString());
if (result == ID2LUserContext.RESULT_OKAY) {
return sb.toString();
// if the timestamp is invalid and we haven't exceeded the retry
// limit then the call is made again with the adjusted timestamp
} else if (result == userContext.RESULT_INVALID_TIMESTAMP
&& attempts > 0) {
return getValanceResult(userContext, uri, query, sPost, sMethod, attempts - 1);
} else {
sError = sb + " " + result;
}
} catch (IllegalStateException e) {
return "Error: Exception while parsing";
} catch (FileNotFoundException e) {
// 404
return "Error: URI Incorrect";
} catch (IOException e) {
}
return sError;
}
There is a php code snippet I can share from a project that uses the api (same rough logic with java). The User context just prepares the url and the framework of the specific environment (java runtime, or php library) is used to do the post and retrieve the results (in this case it is using php CURL).
$apiPath = "/d2l/api/le/" . VERSION. "/" . $courseid . "/content/isbn/";
$uri = $opContext->createAuthenticatedUri ($apiPath, 'POST');
$uri = str_replace ("https", "http", $uri);
curl_setopt ($ch, CURLOPT_URL, $uri);
curl_setopt ($ch, CURLOPT_POST, true);
$response = curl_exec ($ch);
$httpCode = curl_getinfo ($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo ($ch, CURLINFO_CONTENT_TYPE);
$responseCode = $opContext->handleResult ($response, $httpCode, $contentType);
$ret = json_decode($response, true);
if ($responseCode == D2LUserContext::RESULT_OKAY)
{
$ret = "$response";
$tryAgain = false;
}
elseif ($responseCode == D2LUserContext::RESULT_INVALID_TIMESTAMP)
{
$tryAgain = true;
}
elseif (isset ($ret['Errors'][0]['Message']))
{
if ($ret['Errors'][0]['Message'] == "Invalid ISBN")
{
$allowedOrgId[] = $c;
}
$tryAgain = false;
}
A sample of a trace of a post message is:
PUT https://valence.desire2learn.com/d2l/api/lp/1.0/users/3691?x_b=TwULqrltMXvTE8utuLCN5O&x_a=L2Hd9WvDTcyiyu5n2AEgpg&x_d=OKuPjV-a0ZoSBuZvJkQLpFva2D59gNjTMiP8km6bdjk&x_c=UjCMpy1VNHsPCJOjKAE_92g1YqSxmebLHnQ0cbhoSPI&x_t=1336498251 HTTP/1.1
Accept-Encoding: gzip,deflate
Accept: application/json
Content-Type: application/json
{
"OrgDefinedId": "85033380",
"FirstName": "First",
"MiddleName": "Middle",
"LastName": "Last",
"ExternalEmail": "me#somehostname.com",
"UserName": "Username",
"Activation": {
"IsActive": true
}
}