0

I'm trying to connect to my server by HTTP and obtain a JSON object, but it seems that I can't do it.

Here's my code:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Conector {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("https://falseweb/select_all.php");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);

            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                System.out.println(entity1.getContentEncoding());
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }


        } finally {
            httpclient.close();
        }
    }

}

But instead of the JSON I get a printed null. I already tried the php file and it works, returning a json. Any idea what I'm doing wrong?.
The connection works because i got this message :

 HTTP/1.1 200 OK
Praveen
  • 1,791
  • 3
  • 20
  • 33

1 Answers1

1

You seem to be logging out the content encoding as opposed to the actual content of the response which is probably why you aren't having any JSON joy.

Give the following a go (using Apache Commons IOUtils) :

System.out.println(IOUtils.toString(entity1.getContent(), "UTF8"));

If you can't use IOUtils then you can use any method of converting the InputStream into a String. More on that here.

Tom Mac
  • 9,693
  • 3
  • 25
  • 35