Android JSON receive issue - java

I have a string problem, I used the below code for recieving JSON data from an URL, the code is working fine, but the problem is I am not getting full data only half of the JSON values are coming, I would like to know whether there is reason for this, if so means how to solve this problem. JSON string is very big
DefaultHttpClient http_client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
HttpResponse response = http_client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
int n = in.read(b);
while(n>0){
out.append(new String(b, 0, n));
n = in.read(b);
}
String resultdata = out.toString();
Log.d("Out data",resultdata);

Try getting data like this using BufferedReader
String line="";
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
// Read response
while ((line = rd.readLine()) != null) {
total.append(line);
}
String jsonString=total.toString();

InputStream is = entity.getContent();
BufferedReader out = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = out.readLine()) != null) {sb.append(line + "\n");
}
is.close();
String json = sb.toString();
try this

Please try this,
public static JSONObject getJson(String url){
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
return null;
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),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) {
return null;
}
// Convert string to object
try {
jsonObject = new JSONObject(result);
} catch(JSONException e) {
return null;
}
return jsonObject;
}}

you have to remove this line
int n = in.read(b);
and add
int n=0;
while ((n= in.read(b)) != null)

Related

StringBuilder lost data when convert to String

here what's the problem
I have problem when I tried to get String from my StringBuilder
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 128 * 1024);
StringBuilder dataResponseSB = new StringBuilder();
String line ;
while ((line = reader.readLine()) != null) {
dataResponseSB.append(line);
if (DataFactory.DEBUG_MODE) {
// all data here are complete
Log.i("===LoadDataActivity","line: "+line);
}
}
String rawdata = new String(dataResponseSB); // dataResponseSB.toString(); also not work
if (DataFactory.DEBUG_MODE) {
// data here are lost
Log.i("===LoadDataActivity","rawdata: "+rawdata);
}
(-) I receive a huge data from BufferedReader .readLine()
(-) I use Log to check and sure that I got about 5 line of 8000 Buffer Size per line and I am very sure that I have receive all data properly
(1) I append each line to StringBuilder Here
(-) after I append all the line to StringBuilder
(2) I try to convert it back to String
(-) Now, the problem, the when I check to new String here, the data have only 8192 (it should contain at least 30,000 or more)
What is the problem ? I am not sure it lost when it append to StringBuilder(1) or it lost when it convert back to String (2)
I add the code that I have tried below here ,, I have tried both UTF8 and without UTF8
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, );
params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);
HttpClient client = new DefaultHttpClient(params);
// HttpClient client = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(DataFactory.REQUEST_API_URL + "?id=" + DataFactory.USER_ID );
// Depends on your web service
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpConnectionParams.setSocketBufferSize(client.getParams(), 128 * 1024);
HttpResponse response = client.execute(httppost);
//response.setParams(client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024));
//String rawdata = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
// String rawdata = EntityUtils.toString(response.getEntity());
String rawdata = getResponseBody(response.getEntity());
//Scanner s = new Scanner(response.getEntity().getContent()).useDelimiter("\\A");
//String rawdata = s.hasNext() ? s.next() : "";
/*
//BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// ===================
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 128 * 1024);
StringBuilder dataResponseSB = new StringBuilder();
String line ;
while ((line = reader.readLine()) != null) {
dataResponseSB.append(line);
if (DataFactory.DEBUG_MODE) {
Log.i("===LoadDataActivity","line: "+line);
}
}
dataResponseSB.trimToSize();
String rawdata = new String(dataResponseSB);
/*
InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
StringBuffer sb = new StringBuffer();
int c;
while ((c = reader.read()) != -1) {
sb.append((char)c);
if (DataFactory.DEBUG_MODE) {
//Log.i("===LoadDataActivity","line: "+line);
}
}
*/
I'm pretty sure this is the problem:
Log.i("===LoadDataActivity","rawdata: "+rawdata);
You're assuming that a log entry can include all of your data - I believe each log entry is limited to 8192 characters.
I suggest you log rawdata.length() and you'll see that it's actually got all of the data - it's just logging it that's failing.
try this,,
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
System.out.println("GEN END : " + Calendar.getInstance().getTimeInMillis());
return buffer.toString();
}
// Try this way,hope this will help you to solve your problem...
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
System.out.println("Buffer : " + buffer.toString());

Transfering Base64 String over Http REST service with JSON response

I have a webservice that returnds a json response , the json response contains both plain text and base64 encoded images , I am consuming that service using android app so I implemented progress bar to indicate the progress .
Implementing progress bar forces me to use BufferedInputStream to read the response and update the progress based on what the app is reading .
The problem is that everything is working fine and the progress is updating correctly, but after collecting the response and exiting the while loop , I try to convert the string into json format using JSONObject.
Here is the code snippet
BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
StringBuilder sb = new StringBuilder();
String line = null;
int total = 0 ;
int count = 0 ;
byte[] buffer = new byte[4096];
StringBuffer sBuffer = new StringBuffer();
StringWriter sw = new StringWriter();
String content = new String();
while((count = bis.read(buffer)) > 0){
content += new String(buffer,Charset.defaultCharset());
total += count;
publishProgress(""+(int )total*100/this.contentSize);
Log.i("updating",""+(int )total*100/this.contentSize);
}
bis.close();
// String content = new String(sb);
// Log.i("ServerRawresponse",content);
try {
Log.i("REsponse_Content",content.replaceAll("\"", ""));
responseString = new JSONObject(new JSONTokener(content.replaceAll("\"", "\\\"")));
//System.out.println(content);
} catch (JSONException e) {
e.printStackTrace();
}
Any help please
Try this methods works perfectly with me
HttpResponse WSresponse = httpclient.execute(httppost);
String response = getResponseBody(WSresponse.getEntity());
JSONObject jobj = new JSONObject(response);
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}

XML Request with HttpClient throws Null Exception

try
{
String xmlReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request_inquiry><partner_id>0999</ partner_id><terminal_type>6012</ terminal_ type><product_code>4001</product _code><date_time>20130715115100</date_time><trx_id>SDFSF11234424ADFA</trx_id><data><cust_id>030913320611</cust_id></data></request_inquiry>";
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
HttpPost httpPost = new HttpPost("202.169.43.53:52056/transaction");
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=ISO");
// httpPost.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(xmlReq.length()));
StringEntity se = new StringEntity(xmlReq, ContentType.TEXT_XML);
httpPost.setEntity(se);
System.out.println("Request>>"+httpPost);
StringBuilder html = new StringBuilder("");
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() != 200) {
InputStream in = httpResponse.getEntity().getContent();
byte b[] = new byte[1024] ;
while(in.read(b) != -1) {
html.append((new String(b)).toString());
b = new byte[1024];
}
System.out.println("Output HTML>> "+html.toString());
}
else{
InputStream in = httpResponse.getEntity().getContent();
byte b[] = new byte[1024] ;
while(in.read(b) != -1) {
html.append((new String(b)).toString());
b = new byte[1024];
}
System.out.println(html);
}
} catch (Exception ex) {
throw new SystemException(Common.ERROR_OTHER, ex.getMessage());
}
}
catch(Exception ex) {
System.out.println("Exception>>"+ex.getMessage());
}
I've tried many ways to send XML request to server. and one of the way is look likes the code above. And I have no idea why throws NullException? Is there something wrong with my code? Thanks for help.
The actual exception is in the line
HttpPost httpPost = new HttpPost("202.169.43.53:52056/transaction");
saying
java.lang.IllegalArgumentException
at java.net.URI.create(URI.java:841)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:76)
at Test.main(Test.java:22)
Caused by: java.net.URISyntaxException: Illegal character in scheme name at index 0: 202.169.43.53:52056/transaction
at java.net.URI$Parser.fail(URI.java:2810)
at java.net.URI$Parser.checkChars(URI.java:2983)
at java.net.URI$Parser.checkChar(URI.java:2993)
at java.net.URI$Parser.parse(URI.java:3009)
at java.net.URI.<init>(URI.java:577)
at java.net.URI.create(URI.java:839)
... 2 more
It is because the URI is missing the protocol like http:// or https://
Ex:
try {
String xmlReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request_inquiry><partner_id>0999</ partner_id><terminal_type>6012</ terminal_ type><product_code>4001</product _code><date_time>20130715115100</date_time><trx_id>SDFSF11234424ADFA</trx_id><data><cust_id>030913320611</cust_id></data></request_inquiry>";
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 30);
httpClient.getParams().setParameter(
CoreConnectionPNames.SO_TIMEOUT, 30);
HttpPost httpPost = new HttpPost("http://202.169.43.53:52056/transaction");
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=ISO");
// httpPost.setHeader(HttpHeaders.CONTENT_LENGTH,
// Integer.toString(xmlReq.length()));
StringEntity se = new StringEntity(xmlReq, ContentType.TEXT_XML);
httpPost.setEntity(se);
System.out.println("Request>>" + httpPost);
StringBuilder html = new StringBuilder("");
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
InputStream in = httpResponse.getEntity().getContent();
byte b[] = new byte[1024];
while (in.read(b) != -1) {
html.append((new String(b)).toString());
b = new byte[1024];
}
System.out.println("Output HTML>> " + html.toString());
} else {
InputStream in = httpResponse.getEntity().getContent();
byte b[] = new byte[1024];
while (in.read(b) != -1) {
html.append((new String(b)).toString());
b = new byte[1024];
}
System.out.println(html);
}
} catch (Exception ex) {
ex.printStackTrace();
}
Note: When you are logging exceptions make sure you log the stack trace as well, since it will give you more details about the exception like which class, method and line caused the exception.

getJsonStringFromURL() return a null string

I'm trying to get a json string from a url and my method is returning a null string value when I use this line of code:
String jsonStr = getJsonStringFromURL(url);
Here is the method I'm using:
public static String getJsonStringFromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
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) {
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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) {
return null;
}
return result;
}
I have a url variable used where when I copy and paste the url into a browser it does return and display a json string. Any suggestions or help would be greatly appreciated.
The thing is you assigning value to the result when BufferReader is closed. Thats why you getting the null value.
Instead of assigning result = sb.toString(); outside of the BufferReader assign it before closing it.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
System.out.println(result);// It will print you the value
is.close();
Hope it helps.

json data fetched from php and store them in an array in java

My JSON array is this:
{"Name_1":1,"Name_2":0,"Name_3":0}
and my code in java for getting the values and store them in a separate array is the following:
int[] operations= new int[3];
String result = "";
InputStream is = null;
StringBuilder sb=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testteamgr.netau.net/parsing/test.php");
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);
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{
JSONObject json_data = new JSONObject(result);
System.out.println("Length of json is"+jArray.length());
for(int i=0;i<jArray.length();i++){
if (i==0) operations[0]=json_data.getInt("Name_1");
else if (i==1) operations[1]=json_data.getInt("Name_2");
else if (i==2) operations[2]=json_data.getInt("Name_3"); }
and I am getting those errors:
value br of type java.lang.string cannot be converted to jsonobject
If I print out the result I do not see the JSONobject but the html code.
So what I want is to get these 3 values into a separate array.
You have an object, not an array. To process the result you can use following code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
String[] values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}

Categories