3

I have following code where I am calling an API which is a PHP built. The code returns json stated as below which I am collecting in a stringBuilder object. Problem is its working on some carriers and on few devices with other carriers / wifi connection its throwing JSONException end of input at character 0 exception, i know this comes when input string is empty, it means stringBuilder object is empty. Problem is i don't have access to the devices on which its throwing these errors.

I am not getting on some device why following code returns empty string and on some its working fine, user has tested on 3G as well as wifi these devices are in other country on different carriers.

            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost postRequest = new HttpPost(ServiceUrls.base_url + ServiceUrls.get_profile_url);

            JSONObject object = new JSONObject();
            object.put("username", params[0]);

            StringEntity input = new StringEntity(object.toString());
            input.setContentType("application/json");
            postRequest.setEntity(input);

            HttpResponse response = httpClient.execute(postRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
            StringBuilder stringBuilder = new StringBuilder();
            while ((output = br.readLine()) != null) {
                stringBuilder.append(output);
            }

If it was for all API call then it was logical but doest happen for other API call, this API call returns bigger size JSON string as follows in stringbuilder

{
"status":1, "parking":{
"name":"ghgjjghghg", "cost":3, "ownerId":29, "address":"xyz pqr", "slots":4, "image":"d4bc95c1dd031685746f2c3570788acf.jpg", "details":"gjhjghjgg", "amenities":"gjhg", "id":70, "lon":73.7898023, "lat":19.9974533, "type":0, "available":1 }, "rating":0, "ratingCount":0, "owner":{
"id":29, "username":"vd@gmail.com", "password":"", "fullname":"vi hdjh", "phone":"23434fddf", "ccNum":null, "ccType":null, "type":1, "authType":1, "image":"582e3a77d76ae3203cfd6d6a346da429.jpg", "dni":"abc123", "account":"ABCBANK" } }

I have no clue whats happening , please help. Any input will be appreciated.

vishal dharankar
  • 7,536
  • 7
  • 57
  • 93
  • The code you posted doesn't *return* anything. Are you saying that `stringBuilder` is null? Or that it contains no characters? Or something else? – azurefrog Mar 31 '16 at 19:57
  • Yes @azurefrog stringbuilder is null – vishal dharankar Apr 01 '16 at 05:49
  • The StringBuilder is *not* null. It is *empty.* The condition you describe happens when the input is *empty*. It is impossible to help you if you can't be accurate. – user207421 Apr 01 '16 at 07:31
  • @EJP thanks for correcting , if you know that much would appreciate any help instead of a gracious down vote and a close flagging . – vishal dharankar Apr 01 '16 at 09:57
  • 2
    @vishal *Non sequitur.* It does not follow from the fact that I can spot an obvious error in your post that I know what is happening with all your devices. You don't have any evidence about downvotes or close votes on this question. You need to stop guessing about everything here. – user207421 Apr 03 '16 at 12:15
  • It happens only when server response are `empty`. – Amitsharma Apr 06 '16 at 12:29
  • Could you be a bit more specific on which line you get the exception? – uniknow Apr 08 '16 at 19:56
  • Other things that could provide a hint on why it is failing could be to print the statusline of the http response, the content type,length and encoding of the http entity and – uniknow Apr 08 '16 at 20:03
  • Yep I think I will do that – vishal dharankar Apr 09 '16 at 07:31
  • @uniknow error is when try to parse json but I think it's obvious as input is empty – vishal dharankar Apr 09 '16 at 07:32
  • If the returned JSON (confirmed by fact that length of entity is 0) is empty wouldn't that indicate there is something wrong at the side that creates the JSON part? – uniknow Apr 09 '16 at 08:29
  • @uniknow accept it but this issue arises on few devices with different carrier and wifi networks and not all , so I m looking for a hint – vishal dharankar Apr 09 '16 at 09:19
  • All devices have same version of software installed and is it consistent on those devices or sometimes? By the way, did you manage to print statusline of the http response, the content type,length and encoding of the http entity? (on success and failure). – uniknow Apr 09 '16 at 14:03

3 Answers3

3

There is nothing unusual about the code you posted. No clues there.

Let me summarize what I think you said about the symptoms.

  • For some devices / carriers, a specific API call fails. But not all devices / carriers.

  • For the same devices / carriers as above, other API calls work, all if the time.

  • The client-side code is identical in all cases, apart from the URLs.

To me, this is pointing at a problem on the server side that is triggered by what the requests look like to it. But either the way, I would try to investigate this by looking at the requests and responses on the server side, and checking the server-side logs. See if there are significant differences in the requests coming from different devices / carriers. Especially the ones that work versus the ones that don't work. And see if the responses are empty when the server sends them.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

I found the theory of Leonidos usefull: https://stackoverflow.com/a/19540249/6076711

And here is my end of solution you can try using the following code.

string output = "";
while(br.ready() && (br.readLine() != null))
{
    output += (String.valueOf(br.readLine()))+"\n";
}
Community
  • 1
  • 1
0

The code can be improved by checking (before putting it in the string builder) whether the length of the content is bigger than 0.

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(ServiceUrls.base_url + 
        ServiceUrls.get_profile_url);

JSONObject object = new JSONObject();
object.put("username", params[0]);

StringEntity input = new StringEntity(object.toString());
input.setContentType("application/json");
postRequest.setEntity(input);

HttpResponse response = httpClient.execute(postRequest);

String output;

if (response.getStatusLine().getStatusCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatusLine().getStatusCode());
} else {
    HttpEntity entity = response.getEntity();

    if ((entity != null) && (entity.getContentLength() != 0)) {
        // Use writing to output stream to prevent problems with chunked responses    
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       entity.writeTo(os);
       output = new String(os.toByteArray(),"UTF-8"); 
    } else {
       // Handle case there is not content returned
       System.out.println("Received no content (HTTP response code " + response.getStatusLine().getStatusCode() + " , reason: " + getReasonPhrase() +")");
    }
}

The code above however doesn't solve the issue why you get an empty response. I its only handling the fact it is happening is a more elegant way.

I noted however that you require a username in the request. Are you sure the user exist on the device and in case of non existing user, should there be returned something else?

uniknow
  • 938
  • 6
  • 5