【问题标题】:how to use xml parsing in android using retrofit如何使用改造在android中使用xml解析
【发布时间】:2019-03-14 03:48:57
【问题描述】:

我是 android 新手,我想使用改造来解析 xml 文件,我已经浏览了在 stackoverflow 中发布的链接
How to use Retrofit and SimpleXML together in downloading and parsing an XML file from a site? 但在我的场景中,我必须添加标题,我如何使用 Retrofit 来实现这一点。

下面是xml解析器

【问题讨论】:

    标签: android xml-parsing retrofit2


    【解决方案1】:

    不带标头的示例 Web 服务:

    public interface ApiService {
        @GET("/webservice/xml")
        Call<YourClass> getXml();
    }
    

    这是我们添加静态和动态标题的方式:

    public interface ApiService {
        @Headers({"Accept: application/json"})
        @GET("/webservice/xml")
        Call<YourClass> getXml(@Header("Authorization") String authorization);
    }
    

    使用 ApiService:

    new Retrofit.Builder()
    .baseUrl("server ip")
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .build().create(ApiService.class).getXml("This is a value that will be sent as authorization header");
    

    为了使用此代码,您应该将这些行添加到您的 gradle 文件中:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile('com.squareup.retrofit2:converter-simplexml:2.1.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }
    

    这里有一个很好的教程https://futurestud.io/tutorials/retrofit-add-custom-request-header

    【讨论】:

    【解决方案2】:

    header 为静态值的示例接口:

    public interface ApiService {
    
        @Headers("user-key: 9900a9720d31dfd5fdb4352700c")
        @GET("api/v2.1/search/webxml")
        Call<String> getRestaurantsBySearch(@Query("q"), String query);
    
    }
    

    以header为参数的示例接口:

    public interface ApiService {
    
        @GET("api/v2.1/search/webxml")
        Call<String> getRestaurantsBySearch(@Query("q"), String query, @Header("user-key") String userkey);
    
    }
    

    【讨论】:

    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2016-02-25
    • 2017-07-07
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多