HttpClientJava GET JSON无法正常工作

时间:2017-11-16 10:39:56

标签: java json apache httpclient

我尝试通过HTTP连接到我的服务器并获取JSON对象,但似乎我无法做到。

这是我的代码:

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

}

但是我没有使用JSON,而是获得了打印空值。我已经尝试过php文件并且可以正常工作,返回一个json。知道我做错了吗?
连接有效,因为我收到了此消息:

 HTTP/1.1 200 OK

1 个答案:

答案 0 :(得分:2)

您似乎正在注销内容编码而不是响应的实际内容,这可能是您没有任何JSON乐趣的原因。

给出以下内容(使用Apache Commons IOUtils):

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

如果您无法使用IOUtils,则可以使用将InputStream转换为String的任何方法。更多关于here