HttpURLConnection返回类似DefaultHttpClient的响应

时间:2016-08-20 12:55:12

标签: java android http response httpurlconnection

我有一个使用DefaultHttpClient执行http请求的旧代码,我试图将其转换为HttpURLConnection,但我在回复时遇到了麻烦。

以下是原始代码:

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }

这就是我想要做的事情:

    HttpURLConnection conn = null;
    URL url;
    try
    {
        url = new URL(serviceUrl);
    }
    catch (MalformedURLException e)
    {
        throw new IllegalArgumentException("invalid url: " + serviceUrl);
    }

    try {

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.connect();
        //Don't know what to do now to return the response(?)
    }

但我不知道怎么做才能得到与回应相同的结果。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

InputStream inputStream = conn.getInputStream();
StringBuilder build = new StringBuilder();
    if (inputStream != null) {
        InputStreamReader ISreader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(ISreader);
        String line = reader.readLine();
        while (line != null) {
            build.append(line);
            line = reader.readLine();
        }
    }
return build.toString();

在此代码中,您将从InputStream获取HttpUrlConnectionInputStreamReader用于使用BufferedReaderDim mainTable = "CREATE TABLE IF NOT EXISTS users (userID INTEGER PRIMARY KEY, name VARCHAR(20))" Dim typeTable = "CREATE TABLE IF NOT EXISTS userType (type VARCHAR(20), user INTEGER, FOREIGN KEY(user) REFERENCES users (userID))" 获取回复。