JSON: "Unexpected character (<) at position 0" - java

Here's the twitch.tv api request to get channel summary: http://api.justin.tv/api/streams/summary.json?channel=mychannel. If I post it via browser, I get correct results. But programmatically I receive an exception during result parsing.
I use apache HttpClient to send requests and receive responses. And JSON-Simple to parse JSON content.
This is how I try to get JSON from response according to api:
HttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(new URL("http://api.justin.tv/api/streams/summary.json?channel=mychannel").toURI());
getRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String output;
StringBuilder builder = new StringBuilder();
while((output = br.readLine()) != null) {
builder.append(output);
}
br.close();
JSONParser parser = new JSONParser();
Object obj = parser.parse(builder.toString()); //Exception occurs here
Expected result: {"average_bitrate":0,"viewers_count":"0","streams_count":0}, but execution of example above leads to: Unexpected character (<) at position 0.
How to get JSON body from response? Browser displays the result correct.

Try this:
URL url = new URL("http://api.justin.tv/api/stream/summary.json?channel=mychannel");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
InputStream is = request1.getInputStream();
BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = bf_reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
String responseBody = sb.toString();
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseBody);
System.out.println(obj);

Related

java how to receive web service response in JSON

i am new to web services i am calling a web service that should returns JSON with the folliwng code - the problem is i am getting the response in xml format
when i am trying the same parameters using google rest api - the response is in jSON
any ideas what i am doing wrong ?
public static String getSFData(String urlSuffix) throws MalformedURLException, ProtocolException , IOException
{
String header = "Basic XXXXX";
URL url = new URL("https://api2.successfactors.eu/odata/v2/"+urlSuffix);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("authorization",header);
connection.setRequestProperty("Content-Type", "application/json");
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bf.readLine()) != null )
{
stringBuffer.append(line);
}
String response = stringBuffer.toString();
System.out.println("response"+response);
return response;
}
UPDATE
You could try the API URL like http://api2.successfactors.eu/odata/v2/User?
$format=json to get data in JSON.
Use StringBuilder instead of StringBuffer.
Try the following after set content type.
connection.connect();
int status = connection.getResponseCode();
switch (status) {
case 200:
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
String response = stringBuilder.toString();
System.out.println("response : " + response);
}

HttpURLConnection update from Http Client

Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one&param3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}

Can't properly parse JSON

I am having some issues while parsing JSON response in Android. The response I get is:
{
"response": "{\"session_token\":\"48500d8e42acc09aa45cb8f3a7ba2b30\",\"user_login\":\"newoff2\",\"user_id\":\"62\",\"user_profile_img\":\"http://onepgr.com/system/photos/62/medium/userfile054c35e29.png?1422089771\",\"success\":\"0\",\"user_email\":\"newoff2#pdmoffice.com\"}"
}
I need the values for user_login, success, user_profile_img, user_email. Here is what I tried so far, but it won't do what I need:
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
Log.d("Final Response",json);
jsonObject = new JSONObject(json);
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
Log.e("Parsed data is",str);
use this
json=json.replace("\\\"", "\"");
Log.e("resule",json);
try {
JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use regex to make your string JSON parsable
var res = data.replace(/\\"/g, '').replace(/\"{/g, '{').replace(/\}"/g, '}');
var jsonData = JSON.parse(res);
alert(jsonData.response.user_login);
Here is FIDDLE
Note: in fiddle I have declared your JSON with a ' ' to make it complete string
Use Scanner to remove \:
String resultStr = new Scanner(json).useDelimiter("\\A").next();
jsonObject = new JSONObject(resultStr);
Above is used for BufferedInputStream to get JSON string.
[UPDATE:]
For BufferReader, need to use StringBuilder to get JSON string:
StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
//for your JSON string, should use 'JSONTokener' to parse
jsonObject = (JSONObject) new JSONTokener(strBuilder.toString()).nextValue();
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
This should work for your case!
Try this....
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Result",result);
JSONObject jsonObject = new JSONObject(result);
String resJson=jsonObject.getString("response");
Log.d("Result",resJson);
JSONObject jsparam=new JSONObject(resJson);
String success=jsparam.getString("success");
Log.d("Value for success",success);
// JSONObject json1=jsonObject.getJSONObject("response");
//String objResponse = json1.getString("success");
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Android HTTP Post Request doesn't work, but stock Java does?

So I have 2 codes which supposedly do the same. The one I'm using on Android however, returns the wrong HTML data. The stock Java one returns the correct data after sending the request. I have both codes here. Can you tell me (EVEN THOUGH I GAVE INTERNET PERMISSION TO ANDROID) why the Android one isn't working, while the stock Java one is working? This is the Android code:
EDIT: I FOUND THE FIX. If you're going to use a StringEntity to send such a String to the Server, you have to set the content to application/x-www-form-urlencoded. I've edited my code to show this:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
StringEntity se = new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3");
se.setContent("application/x-www-form-urlencoded");
post.setEntity();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
This is the stock Java code:
public String sendNamePostRequest(String urlString) {
StringBuffer sb = null;
try {
String data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3";
// String data = "";
URL requestUrl = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
dos.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
If the data is getting to the server, you might want to see what is happening there (logs, errors, exceptions, etc.) Other than that:
use can use HttpURLConnection, so you can have the exact same code
For HttpClient, not sure whey you are encoding the entity yourself. Use NameValuePair to set parameters, and HttpClient will encode them for you (correctly).
You can use NameValuePair and UrlEncodedFormEntity:
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(KEY1, VALUE1));
nvps.add(new BasicNameValuePair(KEY2, VALUE2));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.setEntity(p_entity);

Error converting a HTTP POST response to JSON

When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.

Categories