import com.example.hoofdgebruiker.winkelskortrijk.Interfaces.ODKortrijkInterface;
import com.example.hoofdgebruiker.winkelskortrijk.Model.Winkel;
public class ODKortrijkWebservice extends AsyncTask<ODKortrijkInterface, Void, String>{
private ODKortrijkInterface listener;
@Override
protected String doInBackground(ODKortrijkInterface... arg0) {
listener = arg0[0];
StringBuilder newsBuilder = new StringBuilder();
// execute search
try {
//HttpGet newsGet = new HttpGet("http://data.drk.be/kortrijk/nieuws.xml");
HttpGet newsGet = new HttpGet("http://data.kortrijk.be/nieuws/rss.xml");
HttpResponse newsResponse = newsClient.execute(newsGet);
StatusLine newsSearchStatus = newsResponse
.getStatusLine();
if (newsSearchStatus.getStatusCode() == 200) {
// we have an OK response
HttpEntity newsEntity = newsResponse.getEntity();
InputStream placesContent = newsEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(
placesContent);
BufferedReader placesReader = new BufferedReader(
placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
newsBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return newsBuilder.toString();
}
protected void onPostExecute(String result) {
ArrayList<NewsItem> newsItems = processResult(result);
listener.updateScreen(newsItems);
}
private ArrayList<NewsItem> processResult(String result){
ArrayList<NewsItem> newsItems = new ArrayList<NewsItem>();
NewsItem newsItem= new NewsItem();
try {
// parse XML
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(result));
int eventType = xpp.getEventType();
boolean isItem = false;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")){
newsItem= new NewsItem();
isItem=true;
} else if (xpp.getName().equalsIgnoreCase("title") && isItem){
xpp.next();
newsItem.setTitle(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("link") && isItem){
xpp.next();
newsItem.setLink(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("description") && isItem){
xpp.next();
newsItem.setDescription(xpp.getText());
newsItems.add(newsItem);
isItem=false;
}
}
eventType = xpp.next();
}
}
catch (Exception e) {
e.printStackTrace();
}
return newsItems;
}
}
我必须做类似的事情,但是对于不同的web服务。但是,org.apache.http导入在较新版本中不起作用。我可以回到旧版本,但这似乎并不是最佳的。目前做这样的事情是什么(连接到web服务和读取数据)?任何人都可以给我一个简单的例子,或解释我应该做什么?谢谢
答案 0 :(得分:0)
现在Android支持HttpURLConnection而不是Apache Http,
你可以在这里找到一些参考资料:
https://developer.android.com/training/basics/network-ops/connecting.html
https://developer.android.com/reference/java/net/HttpURLConnection.html
此外,您应该检查改造: