簡體   English   中英

Android 對 API url 的簡單 POST 和 GET 請求

[英]Android Simple POST and GET requests to an API url

我對標題描述的主題很陌生,而且我有點迷茫,所以我需要一些指導。 基本上,首先我想從 API 向 URL 發出 POST 請求。 然后檢查用戶是否成功登錄並獲取不記名令牌作為響應。 最后,我想發出一個 GET 請求(包括我之前獲得的不記名令牌)以接收其他一些數據(那里有很多產品及其標題、圖像 url 等)。 我想在這兩種情況下我都必須收到一種 JSON。 我在這里檢查了一個類似的主題,我認為它可能會對我進行登錄。 但是,這也適用於之后對其他數據的 GET 請求嗎?

最后,當我得到一個帶有數據的 JSON 時(來自 GET 請求),知道如何將 JSON 的某些部分轉換為字符串 arrays 嗎? (例如,從中獲取產品標題、圖像 url)所以我希望這些 URL 在一個字符串數組和另一個字符串數組中以類似的方式存儲它們的標題等)

非常感謝。

Koush/Ion 示例

在 gradle.build 中添加:

    implementation 'com.koushikdutta.ion:ion:3.1.0'
    implementation 'com.google.android.gms:play-services-base:17.5.0'

這是您將在活動 class 中使用的示例(已測試):

private void post() {
        JsonObject json = new JsonObject();
        // add whatever variables you need
        json.addProperty( "username", "user" );
        json.addProperty( "password", "password" );

        Ion.with( this )
                .load("https://example.com/rest/credentials")
                .setJsonObjectBody( json )
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        // let's suppose the result looks like this: { "result": { "token": "AFDfz553#FF0015" } }
                        String token = result.getAsJsonObject( "result" ).get( "token" ).getAsString();
                        get( token );
                    }
                });
    }

    private void get( String token ) {
        Ion.with( this )
                .load("https://example.com/rest/api/product")
                .addQuery( "token", token )
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        // do stuff with the result or error, for example : {"prod_title" : "The Tittle", "imageUrl" : "blabla"}
                        String title = result.get( "prod_title" ).getAsString();
                        String imgSrc = result.get( "imageUrl" ).getAsString();
                        //etc... or add all values to a List
                        List<String> values = new ArrayList<>();
                        for ( String k : result.keySet() ) {
                            values.add( result.get( k ).getAsString() );
                        }
                    }
                });
    }

Get方法中的addQuery部分將令牌作為參數添加到加載的 url 中。 在上面的示例中,url https://example.com/rest/api/product變為https://example.com/rest/api/product?token=tokenValue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM