小编典典

需要一个简单的android / webservice工作教程?

json

我真的是使用Android的新手,所以让我感到困惑。我看了看似100篇教程以及有关如何从Android上的Web服务获取信息的示例,但是我需要的是对一个毫无头绪的人所需要的东西。以下是我没有得到的特别几点:

  • 我不知道该如何处理XML文件。.意思是,一旦我完成Java工作,就是所有要做的事情吗?还是需要在XML文件中进行任何更改?
  • 似乎我应该为其中一些教程创建一个新类,但是我不确定,如果这样,我不确定一旦完成该类该怎么做
  • 我想以JSON格式检索信息。就目前而言,只要我能获得很好的信息,我就可以稍后学习如何使用JSON。
  • 似乎kSoap2是执行此操作的最佳方法。我有使用它所需的jar文件
  • 我已经深入研究了phonegap,所以如果有一个答案可以解决这个问题,那么我可以解决这个问题

我的Web服务正常运行,并且与我在许多教程中看到的基本相同,因此那里没有问题。

如果有人可以向我指出一个教程,可以帮助我学习创建样本应用程序(从Web服务获取信息)所需的全部知识,或者有人愿意指导我完成本教程,那么我将不胜感激!

提前致谢!


阅读 233

收藏
2020-07-27

共1个答案

小编典典

最初, 您必须建立一个http连接,以便可以从api获得响应,无论是xml响应还是json响应。您可以使用以下代码。
使班级与活动分开。:-

public class Response {

String get_url, response;
Activity activity;

public Response(String url){
    this.get_url = url;

}

public String getResponse(){
     InputStream in = null;        
      byte[] data = new byte[1000];
        try {
              URL url = new URL(get_url);   
              URLConnection conn = url.openConnection();
              conn.connect();
            /*  conn.*/
              in = conn.getInputStream();
              Log.d("Buffer Size +++++++++++++", ""+in.toString().length());
              BufferedReader rd = new BufferedReader(new InputStreamReader(in),in.toString().length());
              String line;
              StringBuilder sb =  new StringBuilder();
              while ((line = rd.readLine()) != null) {
                    sb.append(line);
              }
              rd.close();
              response = sb.toString();

             in.read(data);
          Log.d("INPUT STREAM PROFILE RESPONSE",response);
            in.close();
        } catch (IOException e1) {
            Log.d("CONNECTION  ERROR", "+++++++++++++++++++++++++++");
            // TODO Auto-generated catch block

            e1.printStackTrace();
        }
        return response;
}
}

您可以像这样在活动中上课:-

Response res = new Response("your_url");
String getResponse = res.getResponse();

因此,您可以从api获得响应。

现在,让解析器

         //Extend the class with Default Handler

         public class XMLParser extends DefaultHandler {
              //You must have basic knowledge about Array List and setter/getter methods
              // This is where the data will be stored
       ArrayList<Item> itemsList;
          Item item;
           String data;
            String type;
           private String tempVal;

                 //Create the Constructor
           public XMLParser(String data){
        itemsList = new ArrayList<Item>();

        this.data = data;

    }

     public byte parse(){

            SAXParserFactory spf = null;
            SAXParser sp = null;
            InputStream inputStream = null;

            try {
                inputStream = new ByteArrayInputStream(data.getBytes());
                spf = SAXParserFactory.newInstance();
                if (spf != null) {
                    sp = spf.newSAXParser();
                    sp.parse(inputStream, this);
                }
            }
            /*
             * Exceptions need to be handled MalformedURLException
             * ParserConfigurationException IOException SAXException
             */

            catch (Exception e) {
                System.out.println("Exception: " + e);
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null)
                        inputStream.close();
                } catch (Exception e) {
                }
            }

            if (itemsList != null && itemsList.size() > 0) {
            //  //Log.d("Array List Size",""+tipsList.get(4).getTitle());


                return 1;
            } else {
                return 0;
            }

        }

     public ArrayList<Item> getItemList(){
         return itemsList;
     }


              // Here you can check for the xml Tags
     @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {


         if(localName.equalsIgnoreCase("item")){
             item = new Item();
             Log.d("Working", "+++++++++++++++++++++++");
         }


     }
         //tempVal is the variable which stores text temporarily and you
                 // may save the data in arraylists
     public void characters(char[] ch, int start, int length)
                throws SAXException {
            tempVal = new String(ch, start, length);
        }


     @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {




         if(localName.equalsIgnoreCase("item")){
             itemsList.add(item);
             Log.d("Working in endelement", "+++++++++++++++++++++++");

            item.setTitle(tempVal);

        }
       }

结合所有这些:

现在让我们看一下活动

         public void oncreate(){
               // Do something or mostly the basic code
               // Call the class to initate the connection and get the data
                 FetchList fl = new FetchList();
                  fl.execute();
                  }
          //Always better to use async task for these purposes
           public class FetchList extends asyncTask<Void,Void,Byte>{

                doinbackground{
                    // this was explained in first step
                     Response res = new Response("url");
                     String response = res.getResponse();
                     XmlParser xml = new XmlParser(response);
                      ArrayList<item> itemList = xml.getItemList();
                      xml.parse();
                 }
                }

好了,仅此而已。

2020-07-27