Why isn't the server returning anything?

2019-07-31 18:19发布

问题:

I used the following piece of code to retrieve basically a JSON formatted String from a php page (www.ace.ucv.ro/android/android.php).

For some reason, no matter what I try, the string "result" remains empty, nothing is stored inside it, even when I use a special function to convert it from InputStream to String (with BufferedReader).

The String in which I want to store is called "RESULT".

public void connect(String url){
         HttpClient client = new DefaultHttpClient();
         HttpGet httpGet = new HttpGet(url);
         HttpResponse response;

         try{
             response = client.execute(httpGet);

             Log.i("Praeda", response.getStatusLine().toString());

             HttpEntity entity = response.getEntity();

             if(entity != null){
                 result = entity.getContent().toString();
             }

             if(entity == null){
                 result = "failed";
             }
             }catch(Exception e){
             e.printStackTrace();
         }
    }

Any suggestions you might have would be great...

回答1:

JSON response is normally gzipped, try this

jsonResponse = client.execute(httpGet);
InputStream in = response.getEntity().getContent();
GZIPInputStream gin = new GZIPInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(gin));
String line;
while ((line = reader.readLine()) != null) {
    jsonResponse.append(line);
}
reader.close();