I am working on an English dictionary using an online free API: https://api.dictionaryapi.dev/api/v2/entries/en_US/
The code was working fine just one month ago, but now the returned data is always "error". It is not giving back response :: 200. Could anyone tell me what's wrong with the code?
public String getOnlineData(String word){
String data = "";
String decodeData = "";
try{
URL url = new URL("https://api.dictionaryapi.dev/api/v2/entries/en_US/"+word);//store the url link in the variable url
HttpURLConnection con = (HttpURLConnection)url.openConnection();//start a new connection
if(con.getResponseCode()==200){
InputStream im = con.getInputStream();//store the text result in the variable im
BufferedReader br = new BufferedReader(new InputStreamReader(im));
//read the result using bufferedreader
String line=br.readLine();//read each line
while(line!=null){//stop until there is no line to read
data = data + line;
line=br.readLine();
}
br.close();//close the buffered reader
decoder jd = new decoder();//decode the result
decodeData = jd.Decoder(data);//store the decoded result in decodeData
}
else{
decodeData="error";//if the system doesn't get response, the result will be error
}
}
catch(Exception e){
try{
decodeData="error";//if the connection failed, result is error
System.out.println(e);
}
catch(Exception e1){
System.out.println(e1);
}
}
return decodeData;
}
I am sending image data from my android app to server,I can see in log that string array is not empty and has correct data but on server it receive null.
Here is my AsyncTask from where i am sending data to server
protected Void doInBackground(Void... params) {
BufferedReader reader;
try {
URL url = new URL("http://www.example.com/Data/galleryLog.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Log.d(TAG,"String Data "+Images);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(Images);
writer.flush();
writer.close();
os.close();
connection.connect();
//For POST Only End
int responseCode = connection.getResponseCode();
Log.d(TAG, "POST RESPONSE CODE " + responseCode);
String LoginResult;
if (responseCode == HttpURLConnection.HTTP_OK) {
//Success
Log.d(TAG, "Success connection with database");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
Log.d(TAG, "Reader Close - Printing Result ");
//Print Result
Log.d(TAG, "Calling Response " + response.toString());
}
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is the string i got in logcat which is not empty and has correct data
String Data {"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"image-101.jpg"}],"User_ID":"18","galleryTitle":"Image-101.jpg"}
My Php Code where i am printing received data into file but it give me blank file always
<?php
$tm = 'ritu_gallery_'.time().'.log';
file_put_contents($tm, print_r($_POST, TRUE));
echo "Response<br>";
print_r($_POST);
?>
Its create text file like that
Array ( )
UPDATE: its an issue in AsyncTask String array. I don't know why its not working.If anyone knows please let me know
When i am sending this string array to server.it's print blank values on server
{"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"image-101.jpg"}],"User_ID":"18","galleryTitle":"Image-101.jpg"}
when i add above String array into this
String data= URLEncoder.encode("Pic","UTF-8")+ "=" +URLEncoder.encode(Images,"UTF-8");
It creates file on server like this
Array (
[Pics] => {"galleryDesc":"My First Gallery","images":[{"base64code":"Base64Image","type":"jpg","imagename":"101.jpg"}],"User_ID":"18","galleryTitle":"101.jpg"}
)
with all correct values.If anyone know why this is happening. Please let me know
you are accessing the wrong variable here, an image is a file and it will be in $_FILE variable not in $_POST variable, also the form should be multipart formdata, i don't know if you are doing that or not cause i don't know very much about android but if are doing so then you can see your file in $_FILE variable
I am a new programmer, i am trying to build an app with Json.
I created Json parser class and in my main activity i have the following code :
String url = "http://echo.jsontest.com/key/value/one/two";
JSONObject json = jParser.getJSONFromUrl(url);
one = json.getString(gridArray.get(lekeres).getTitle()); // one has the good value "two"
This works great. BUT
if i change url to : https://api.myjson.com/bins/3f8d2
which is exactly the same code as in the jsontest, one doesn't have "two" . I searched for hours but i don't know why this is happening. I did nothing but change the url. The contest is the same...
Since I don't know how is your parser. I made a quick test and can read both link normally with this code:
try {
//url = new URL(""http://echo.jsontest.com/key/value/one/two2");
url = new URL("https://api.myjson.com/bins/3f8d2");
InputStream is = url.openStream();
JSONObject json = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String jsonText = sb.toString();
json = new JSONObject(jsonText);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is more examples: http://en.proft.me/2013/12/5/how-parse-json-java/.
You can make your getJSONFromUrl similarly. Otherwise like other suggest try without https://.
I have a JSON file with 2 JSON-Arrays in it:
One Array for routes and one Array for sights.
A route should consist of several sights where the user gets navigated to.
Unfortunately I am getting the error:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
Here are my variables and the code that parses the JSON-File:
private InputStream is = null;
private String json = "";
private JSONObject jObj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Log.i("JSON Parser", json);
shows me that at the beginning of the generated string there is a strange sign:
but the error happens here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data
org.json.JSONException: Value //STRANGE SIGN HERE // of type
java.lang.String cannot be converted to JSONObject
anybody has a clue on how to get rid of these signs in order to create the JSONObject?
Reason is some un-wanted characters was added when you compose the String.
The temp solution is
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
But try to remove hidden characters on source String.
see this
http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.
So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.
BTW. i used UTF-8 encoding on both sides.
PHP side: header('Content-type=application/json; charset=utf-8');
JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
So try the solution one by one 1,2,3,4...! Hope it helps you guys!
try {
jObj = new JSONObject(json.substring(3));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
This worked for me
json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Here is UTF-8 version, with several exception handling:
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params, true);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpGet httpPost = new HttpGet( url);
httpResponse = httpClient.execute( httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException ee) {
Log.i("UnsupportedEncodingException...", is.toString());
} catch (ClientProtocolException e) {
Log.i("ClientProtocolException...", is.toString());
} catch (IOException e) {
Log.i("IOException...", is.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8); //old charset iso-8859-1
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
json = sb.toString();
Log.i("StringBuilder...", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (Exception e0) {
Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
Log.e("JSON Parser0", "Error parsing data " + e0.toString());
try {
jObj = new JSONObject(json.substring(1));
} catch (Exception e1) {
Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
Log.e("JSON Parser1", "Error parsing data " + e1.toString());
try {
jObj = new JSONObject(json.substring(2));
} catch (Exception e2) {
Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
Log.e("JSON Parser2", "Error parsing data " + e2.toString());
try {
jObj = new JSONObject(json.substring(3));
} catch (Exception e3) {
Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
Log.e("JSON Parser3", "Error parsing data " + e3.toString());
}
}
}
}
}
// return JSON String
return jObj;
}
This is simple way (thanks Gson)
JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
return response;
After that get the response we need to parse this By:
JSONObject myObj=new JSONObject(response);
On response there is no need for double quotes.
I made this change and now it works for me.
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.
Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.
(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)
Hope it helps.
In my case the problem occured from php file.
It gave unwanted characters.That is why a json parsing problem occured.
Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM
from Encoding tab and running this code-
My problem gone away.
In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.
The error was:
JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject
This is a snippet on how I was constructing the Volley JSON request:
final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);
I solved my problem by creating the JSONObject with an empty JSON object as follows:
final JSONObject emptyJsonObject = new JSONObject("{}");
My solution is along the lines to this older answer.
if value of the Key is coming as String and you want to convert it to JSONObject,
First take your key.value into a String variable like
String data = yourResponse.yourKey;
then convert into JSONArray
JSONObject myObj=new JSONObject(data);
For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):
JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))
I am trying to login to a website using java.net in Google App Engine for Java.
The login id and password are stored in variables 'loginid' and 'password' respectively.
The code that I have created is given below:
public Integer login()
{
String param1="", param2="", query="";
String charset = "UTF-8";
String loginurl = "https://website.com/login";
try {
param1 = URLEncoder.encode(loginid, "UTF-8");
param2 = URLEncoder.encode(password, "UTF-8");
query = String.format("username=%s&password=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
} catch (UnsupportedEncodingException ex) {
// ...
}
try {
URL url = new URL(loginurl + "?" + query);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line="";
String resp="";
while ((line = reader.readLine()) != null) {
resp=resp + line;
}
actionmessage=" Response-" + resp;
return(1);
}
catch (Exception e) {
// ...
}
}
I want to know more about a couple of things with ref to above code.
I am sure that I have entered correct ID and password, but still I am getting login failure. What is wrong with the above code?
How do I check if a submission as made by above code is successful or if there is an error? If there is an error, how do I get the error stream?
It was an error on my part- I encoded the 2 parameters passed to input url, twice!! So the site where I was authenticating, received a garbled value for user id and password!