Android(Java)App将http更新为HttpURLConnection

我当前在API 27上使用我的Android(Java)应用。目前,我仍在旧模式下使用HTTP方法,但是我想切换到HTTPURLConnection以便能够更新到API 28。

要开始使用HTTPURLConnection,我必须添加以下两项:

导入java.net.HttpURLConnection; 导入java.net.URL;

有人给小费吗?

package de.andreas_rothhardt.rssbywapphosting;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class RSSReader implements java.io.Closeable {

private final HttpClient httpclient;


private final RSSParserSPI parser;

public RSSReader(HttpClient httpclient, RSSParserSPI parser) {
this.httpclient = httpclient;
this.parser = parser;
}

public RSSReader(HttpClient httpclient, RSSConfig config) {
this(httpclient, new RSSParser(config));
}

public RSSReader(RSSConfig config) {
this(new DefaultHttpClient(), new RSSParser(config));
}

public RSSReader() {
this(new DefaultHttpClient(), new RSSParser(new RSSConfig()));
}


public RSSFeed load(String uri) throws RSSReaderException {
final HttpGet httpget = new HttpGet(uri);

InputStream feedStream = null;
try {

  final HttpResponse response = httpclient.execute(httpget);


  final StatusLine status = response.getStatusLine();
  if (status.getStatusCode() != HttpStatus.SC_OK) {
    throw new RSSReaderException(status.getStatusCode(),
        status.getReasonPhrase());
  }

  HttpEntity entity = response.getEntity();
  feedStream = entity.getContent();

  RSSFeed feed = parser.parse(feedStream);

  if (feed.getLink() == null) {
    feed.setLink(android.net.Uri.parse(uri));
  }

  return feed;
} catch (ClientProtocolException e) {
  throw new RSSFault(e);
} catch (IOException e) {
  throw new RSSFault(e);
} finally {
  Resources.closeQuietly(feedStream);
}
}


public void close() {
httpclient.getConnectionManager().shutdown();
}

}
评论