1

私はAndroidを初めて使用します.API呼び出しを行って応答を取得するためにいくつかのパラメーターを投稿する必要があるという点でアクティビティを作成しました.Json形式のように、リクエストURLに追加するいくつかのパラメーターを渡す必要があります.どうすればよいか教えてください.私のサンプルURLリクエストは次のとおりです。

http://dev.abctest.com/api/v1/book?customer_firstname=jigar&customer_lastname=jims&customer_mobile=9033309333&customer_email=jigar@epagestore.com&source_country=インド&number_of_travellers=15

以下のようなjson本体のその他のパラメータ:

{

    "destinations": [
        {
            "city_id": 1,
            "start_date": "2014/08/28",
            "end_date": "2014/09/30"
        },
        {
            "city_id": 5,
            "start_date": "2014/08/10",
            "end_date": "2014/09/03"
        }
    ]
}
4

2 に答える 2

1

最初に、URL フィールドをベース URL に追加する必要があります。次に、必要に応じてオプションのフィールドを追加できます。次に、URLが処理後に取得されるHttpPostのエンティティとしてのデータ。

以下を試してください:

  1. 呼び出される親メソッド。

    public void request(String baseUrl,List<NameValuePair> urlFields, List<NameValuePair> formData,List<NameValuePair> optionalData ){
    
    // Append params to the URL 
    if (urlFields != null)
        baseUrl = baseUrl + getUrlPathForGet(urlFields);
    
    // adds Optional fields to the Url
    if (optional != null)
        baseUrl = baseUrl + "?" + URLEncodedUtils.format(optionalData, "utf-8");
    
    postData(baseUrl,formData);
    
    }
    
  2. URLパラメーターをベースURLに追加します

    private String getUrlPathForGet(List<NameValuePair> urlFields) {
    
    String path = "";
    
    if (urlFields != null) {
    
        for (NameValuePair pair : urlFields) {
        path = path + "/" + pair.getValue();
        }
    }
    
    return path;
    }
    
  3. 変更された URL を使用して、フォーム データをエンティティとして HttpPost オブジェクトに追加します。

    public void postData(String baseUrl,List<NameValuePair> formData) {
    
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    // pass the url as parameter and create HttpPost object.
    HttpPost post = new HttpPost(baseUrl);
    
    // Add header information for your request - no need to create 
    // BasicNameValuePair() and Arraylist.
    post.setHeader("Authorization", "Bearer " + token);
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Cache-Control", "no-cache");    
    
    try {       
    
    // pass the content as follows:
    post.setEntity(new UrlEncodedFormEntity(formData,
                        HTTP.UTF_8));
    
    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(post);
    
    // TODO: Process your response as you would like.
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    }
    
于 2014-08-04T11:56:13.013 に答える