【问题标题】:Getting xml from url with HttpURLConnection in Android在Android中使用HttpURLConnection从url获取xml
【发布时间】:2015-11-17 14:36:45
【问题描述】:

我使用支持 Apache HTTP 客户端从 url 获取 xml。

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity, "UTF-8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

Google 宣布从 Android 6.0 开始取消对 Apache HTTP 客户端的支持,并改用 HttpURLConnection 类。 最后,我想使用 HttpURLConnection 从 url 获取 xml,但我不知道!有人可以帮助我:)

【问题讨论】:

    标签: android xml httpurlconnection


    【解决方案1】:

    作为一般提示,由于您没有触及它,我建议在 IntentService 中执行所有 Web 请求,这样它就不会阻塞您的 UI 线程。至于答案,您可以像这样使用 HttpURLConnection

    public String getXMLFromUrl(String url) {
        BufferedReader br = null;
        try {
            HttpURLConnection conn = (HttpURLConnection)(new URL(url)).openConnection();
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
            String line;
            final StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
    
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    这应该不会太难理解,因为代码更改很少,但如果您有任何问题,我很乐意听到他们的声音:)

    【讨论】:

      【解决方案2】:

      您可以尝试修改或使用它作为您的要求如下:

      // Create a new UrlConnection
                  URL postUrl = null;
                  try {
                      postUrl = new URL("Your Url");
                  } catch (MalformedURLException e) {
                      e.printStackTrace();
                  }
                  // Open the created connection to server.
                  HttpURLConnection httpURLConnection = null;
                  try {
                      httpURLConnection = (HttpURLConnection) postUrl.openConnection();
                  } catch (IOException e) {
                      e.printStackTrace();
                      return false;
                  }
                  // Set up the post parameters
                  httpURLConnection.setReadTimeout(10000);
                  httpURLConnection.setConnectTimeout(15000);
      
                  try {
                      httpURLConnection.setRequestMethod("POST or GET");
                  } catch (ProtocolException e) {
                      e.printStackTrace();
                      // Server Error
                      return false;
                  }
      
                  httpURLConnection.setDoInput(true);
                  httpURLConnection.setDoOutput(true);
                  httpURLConnection.setRequestProperty("Content-Type", "text/xml");
      
                  OutputStream outputStream = null;
      
                  try {
                      outputStream = httpURLConnection.getOutputStream();
                  } catch (IOException e) {
                      e.printStackTrace();
                      return false;
                  }
                  // Create a writer to write on the output stream.
                  BufferedWriter writer = null;
                  try {
                      writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                  } catch (UnsupportedEncodingException e) {
                      e.printStackTrace();
                      return false;
                  }
                  // Send the post request
                  try {
                      writer.write();
                      writer.flush();
                      writer.close();
                      outputStream.close();
                      httpURLConnection.connect();
                  } catch (IOException e) {
                      e.printStackTrace();
                      return false;
                  }
                  // Get response code
                  int response = 0;
      
                  try {
                      response  = httpURLConnection.getResponseCode();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  // Get the Response
                  String responseData = "";
                  if(response == HttpURLConnection.HTTP_OK){//Response is okay
                      String line = "";
                      try {
                          BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                          while ((line=reader.readLine()) != null) {
                              responseData += line;
                          }
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
                  else{
                      // Server is down or webserver is changed.
                      return false;
                  }
                  return true;
      

      【讨论】:

        【解决方案3】:

        您可能需要包含一些额外的库

        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.util.EntityUtils;
        

        如果你使用android studio,它可以为你下载jar文件,只需使用Alt+Enter帮助

        【讨论】:

          猜你喜欢
          • 2016-01-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-06
          • 2012-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多