Error converting a HTTP POST response to JSON - java

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.

Related

how to get a json array from php and use its value in android?

i am trying to get the data from database through a php file and then i want to use that data in android.i have tried a lot but it show me this error:type org.json.JSONObject cannot be converted to JSONArray.
followin is my php file and android code.also json array which was return is valid.
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$res = mysqli_query($con,$sql) or die('i cant');
//$result = array();
$abc="";
while($row = mysqli_fetch_assoc($res)){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
$final = array("result"=>$abc);
//echo json_encode(array("result"=>$result));
echo json_encode($final);
mysqli_close($con);
?>
andoid code
public void searchProfession() {
//testin work
String[] stringArray = new String[5];
//
try {
HttpParams httpParams = new BasicHttpParams();
HttpParams p = new BasicHttpParams();
p.setParameter("profession", SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
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);
// 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");
}
result = sb.toString();
// return JSON String
if (inputStream != null) inputStream.close();
//ffffffffffffffffffffffffffff
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//testin work
String[] myarray;
//till here
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString(i);
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0], Toast.LENGTH_SHORT).show();
mylist.add(map);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
My Json : [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id‌​":"76","crtloc_lat":"34.769642","crtloc_lng":"72.361160"},{"user_id":"87","crtloc‌​_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.6971‌​17","crtloc_lng":"72.976631"}]
now i want to get the data in result array and show that data in android.for example i want to use all the(user_id) from that array
I think you got this error because jArray.getJSONObject(0); when i = 0 it's an array not an Object
your Json [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},...]
So jArray.getJSONObject(0); is [] not an object {"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}
You can check out this post on how to execute GET/POST/MULTIPART POST requests in android and then use that post to see how to parse your JSON data into pojo(s).
Hope that helps.
The error:type org.json.JSONObject cannot be converted to JSONArray is thrown when you try to fetch a JSONObject in the place of an array. An exception will also be thrown if you try to fetch empty objects so please check your code for empties.
start by
$abc="";
while($row = mysqli_fetch_assoc($res)){
if(!empty($row['user_id'])&&!empty($row['crtloc_lat'])&&!empty($row['crtloc_lng'])){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
}
Then
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString("crtloc_lat");//Use a key here
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0],Toast.LENGTH_SHORT).show();
mylist.add(map);
}

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

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);

JSON response cutting off part way through

When downloading a JSON array, it cuts off 1/4 of the way through the string, its pretty huge - but it should get the entire string.
There are no errors thrown in the LogCat. This is the method I am using, I have been through it a few times and cant see a reason why it is cutting off. I am pretty new to this however.
public static JSONArray getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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);
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());
}
//try parse the string to a JSON object
try {
Log.d("log_tag", "jresult: " + result + "finish");
jArray = new JSONArray(result);
//Log.e("log_tag", "result: " + jArray.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
I think once this is cracked I will be set. I will make this a class to use in future projects too so I dont have to keep rebuilding it!
EDIT: For loop where markers should be added to map:
try{
for(int i=0;i<arrayResultFromURL.length();i++){
JSONObject json_data = arrayResultFromURL.getJSONObject(i);
// assign attributes from the JSON string to local variables
String id =json_data.getString("id");
String title =json_data.getString("title");
String strap =json_data.getString("strap");
Double lat = (double) json_data.getDouble("lat");
Double lon = (double) json_data.getDouble("long");
theMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(title)
.snippet(strap));
}
}catch (Exception e){
Log.e("log_tag", "error in array: " + e.toString());
}
Maybe your problem comes from the way your are treating the response object. Check this thread.
If not try to check the size of the response first to see if you are receving all.
httpResponse.getEntity().getContentLength()
Also just in case you didn't know there is a nice library (i've been using it since i found it) that simplifies json parsing ckeck it out here.
These type of things can best be done by libraries such as GSON or Jackson
Also, if your goal is to create a JSONArray, there is a constructor that takes in a JSONTokener. JSONTokener can in turn be constructed from your InputStream.

how i can retrieving result from mysql in array?

I want to get results from the database as an array. I have a table "commande" where I have stock. I want to get stock as an array. Something like this: array[0],array[],array[2]
This is the structure of my table commande (idfichecmd idproduit idclt qte datecmd)
This is my code:
String response = null;
String res = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("",));
try {
Log.i("","<<<<<<<<<<<<<<<<<<<<TRY");
response = CustomHttpClient.executeHttpPost("http://0.0.0.0/GetCmdDetails.php",nameValuePairs);
res=response.toString();
// res = res.trim();
//res= res.replaceAll("\\s+","");
//error.setText(res);
} catch (Exception e) {
Log.i("","<<<<<<<<<<<<<<<<<<<<Catch");
}
//parse json data
try{
JSONArray jArray = new JSONArray(res);
//-----------------------------------------
//nom= new String[jArray.length()];
//prenom= new String[jArray.length()];
//----------------------------------------
for (int i=0;i<jArray.length();i++) {
JSONObject json_data = jArray.getJSONObject(i)
First, test if your query is giving the correct result.
I use this solution for getting the jsonarray:
Use HttpClient to call the webservice.
private List<NameValuePair> parameters;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(//yoururl);
int statusCode = -1;
try {
httpPost.setEntity(new UrlEncodedFormEntity(this.parameters));
HttpResponse response = httpClient.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
//Get your inputstream here and convert it to json after
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

Problems with connecting to mysql

Hi am trying to get data from php script in json. I get few errors: first is variable is not resolved. If I try to add new variable like below, then after running app I get error which says Error with converting. It's mainly a tutorial code but there as I said before is a problem with IS variable. Can you help me?
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputSteam is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/bandymas/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream 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);
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());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
I suspect the simple typo in the InputStream declaration might be a place to start.

Categories