我正在尝试从我的andorid应用程序中的 google news rss feed 获取新闻,但我无法得到正确的回复。当我使用邮递员尝试相同时,我得到了回复。
代码:
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("content-type", "application/xml; charset=utf-8");
InputStream is;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
is = connection.getErrorStream();
}
else {
is = connection.getInputStream();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
Resposne:
<HTML><HEAD><TITLE>Not Found</TITLE></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000"><H1>Not Found</H1><H2>Error 404</H2></BODY></HTML>
URL:
https://news.google.com/news/rss/story/dUuojVTpzSeUCKMyoBbnmsAFajvtM?ned=in&hl=en-IN&gl=IN
邮递员的回应:Postman Response
需要更改哪些内容才能获得链接的响应? 任何帮助将不胜感激。
答案 0 :(得分:0)
使用RSS Parser Library可以轻松实现。只需在gradle中添加依赖项,然后就可以执行类似这样的操作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String urlString = "https://news.google.com/news/rss/story/dUuojVTpzSeUCKMyoBbnmsAFajvtM?ned=in&hl=en-IN&gl=IN";
Parser parser = new Parser();
parser.execute(urlString);
parser.onFinish(new Parser.OnTaskCompleted() {
@Override
public void onTaskCompleted(ArrayList<Article> list) {
//what to do when the parsing is done
//the Array List contains all article's data. For example you can use it for your adapter.
Toast.makeText(MainActivity.this,"completed", Toast.LENGTH_SHORT).show();
}
@Override
public void onError() {
Toast.makeText(MainActivity.this,"error", Toast.LENGTH_SHORT).show();
}
});
}