【问题标题】:HttpURLConnection return response like DefaultHttpClientHttpURLConnection 返回响应,如 DefaultHttpClient
【发布时间】:2016-08-20 12:55:12
【问题描述】:

我有一个使用 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(?)
    }

但我不知道如何做才能获得与响应相同的结果。

【问题讨论】:

  • 使用conn.getInputStream()
  • 您想要一种方法来获取响应吗?
  • @Enzokie 好的,谢谢

标签: java android http response httpurlconnection


【解决方案1】:

您可以使用以下内容:

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

在此代码中,您从HttpUrlConnection 获取InputStream,用于使用InputStreamReaderBufferedReader 获取响应。

【讨论】:

  • 好的,谢谢。下次肯定会对我有所帮助,但现在我只需要输入流。
  • 没问题。如果这回答了您的问题,请接受此答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多