Im using the following code to convert from a well-formed-String to a JSONObject in Java:
public void getStatus(){
String status = "";
try{
String line;
StringBuilder result = new StringBuilder("");
HttpURLConnection conn;
URL url;
url = new URL("http://bromio.com.mx/explore/PointOfInterestService.svc/GetData");
BufferedReader rd;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
Log.d("JSON: ", result.toString());
JSONObject jsonObject = new JSONObject(result.toString());
}catch (Exception e){
e.printStackTrace();
}
}
But it's throwing an exception, it seems that i cannot cast that specific string to JSONObject.
The JSON can be acceses in this page: (It's too big to show!) http://bromio.com.mx/explore/PointOfInterestService.svc/GetData
Any help solving this problem will help me a lot. thank you
Let's take the first few characters of your json
"{ \"poi\":[\u000d\u000a
^ ^ ^ ^^^^^^
| | | |-----------> not sure about all this
| | -------------------> not acceptable in json
| ------------------------> not acceptable in json
---------------------------> not acceptable in json
What you get back from that website is not valid root json. Fix your source if you have control over it. Or use the String utility methods to replace those characters.
Related
So I'm facing some difficulty in trying to, what seems simply, obtain a JSON file from a webpage, and then parse it on Android. I have already built the parser, and tested it in Eclipse (in fact, all of the code works in Eclipse). However, when I run the HttpURLConnection and try to retrieve the JSON data in a string in Android Studio, I end up getting no exceptions and an almost empty string (I think I am getting the 1st, 2nd, 3rd, and last character, but not too sure). I have included parts of the code below, and
URL url = null;
HttpURLConnection urc = null;
try {
url = new URL(query);
urc = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urc.getInputStream());
jsoncontent = readStream(in);
System.out.println(jsoncontent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urc.disconnect();
}
The code for readStream() is below
private static String readStream(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
is.close();
return sb.toString();
}
Here is an exact chunk from an assignment I did last semester:
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/html");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JSONObject searchResults = new JSONObject(in.readLine());
...
conn.disconnect();
You seem to be missing setRequestMethod("GET") and setRequestProperty("Accept", "text/html") in your code. Hope this helps.
I have am trying to convert my response from a POST to JSON. And here is what I am doing:
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line).append("\r");
}
rd.close();
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response.toString());
But then I get error java.lang.String cannot be converted to JSONObject
But if I make a string, String string; and then I paste the what I logged and set it equal to string, and then try
JSONObject jsonObject = new JSONObject(string);
It works, so why is it working when I paste the logged response, but not when I just use response.toString();?
In the logcat it looks like this {"url": "www.google.com"}. And then when I paste it into string = "{\"url\": \"www.google.com\"}";
Thanks for the help
I met this problem before, try this:
new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or
if (response != null && response.startsWith("\ufeff")) {
in = in.substring(1);
}
the response from server contains a BOM header
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string.
source - A string beginning with { (left brace) and ending with } (right brace).
So while doing response.toString() if the string do not start with { and close with } then it will throw Exception.
I have implemented reCaptcha in the application I am working on. Somehow I am getting a blank reCaptcha response.
It works fine with localhost, but I am having a problem in upper environments like DEV, TEST. User response is being verified on server side (servlet).
Anyone having idea or faced similar problem ? Let me know if you need more info.
String userresponse = (String) request.getAttribute("g-recaptcha-response");
URL url = null;
HttpURLConnection conn = null;
String line, outputString = "";
try {
url = new URL(https://www.google.com/recaptcha/api/siteverify?secret=privateKey&response=userresponse);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
Log.debug("Google response is :- "+outputString);
} catch (IOException e) {
e.printStackTrace();
}
When I run this code from Java app I get correct response (UTF-8 encoded).
The problem is, when I run it from my servlet, I'm geting:
"פשטות הי� התחכו� המושל�"
ל×�×•× ×¨×“×• די סר פיירו דה ×•×™× ×¦'×™
Any idea how to fix it?
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
String result = "";
try {
url=new URL("http://www.walla.co.il");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String s1="";
String NL = System.getProperty("line.separator");
while ((s1 = rd.readLine()) != null)
sb.append(s1+NL);
System.out.println(sb);
rd.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
set "JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF8"
i run this from *.bat file in my tomcat\bin
and it fix the problem seems like i had to set the encode for tomcat/jvm
not 100% sure but it works now :)
InputStream in = address.openStream();
URL url = new URL("://www.mydomain.com/?param1=NÃO¶m2=NÃO");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
But when i am trying to put the result into StringBuilder the NÃO Special character à is getting escaped
How to bring it with out losing the char set value ?
I believe you want to use URLEncoder.encode(String, String) to encode your parameter like
try {
String value = URLEncoder.encode("NÃO", "utf-8");
String url = "://www.mydomain.com/?param1=" + value + "¶m2="
+ value;
System.out.println(url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Output is
://www.mydomain.com/?param1=N%C3%83O¶m2=N%C3%83O