如何使用okhttp库将Array作为参数传递

时间:2015-12-11 10:32:46

标签: android android-studio okhttp

我正在使用OKHttp依赖。我无法将数组传递给NamvaluePair参数中的服务器。

这是我的函数,用于在POST中发送参数和获取响应中的jSON。

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) throws IOException, JSONException {

 OkHttpClient client = new OkHttpClient();

    Log.i("PARAMETERS", "PARAMETERS ::" + params);

    FormEncodingBuilder builder = new FormEncodingBuilder();

    for (NameValuePair valuePair : params) {

        builder.add(valuePair.name, URLEncoder.encode(valuePair.value, "UTF-8"));
    }

    Request request = new Request.Builder().url(url).post(builder.build()).build();
    Log.i("Registration Request::", request.toString());

    Response response = client.newCall(request).execute();
    Log.i("REGISTRATION RESPONSE::", response.toString());


       JSONObject jObj= new JSONObject(response.body().string()) ;

 return jObj;
}

这是我的号召行动。

public JSONObject getShopCategory(String jsonArray) throws IOException {
        // Building Parameters

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("tag", categoryShopTag));
        params.add(new NameValuePair(categoryShopTag, jsonArray));
        // params.add(new BasicNameValuePair("buyer_id", buyer_id));
        // params.add(new BasicNameValuePair("last_sync_date", last_sync_date));
        Log.i("CATEGORY REQUEST::", params.toString());
        // getting JSON Object
        JSONObject json = null;
        try {
            json = jsonParser.getJSONFromUrl(UrlMap.urlPath, params);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }

这是我称之为功能的地方。

for (int i = 0; i < sellerId.size(); i++) {

                lastdateCat = "2011-02-11 18:57:25";


          buyerCategoryFunction = new BuyerCategoryFunction();

                JSONObject jsonObjectCategory = new JSONObject();
                try {
                    jsonObjectCategory.put("shop_id", sellerId.get(i));
                    jsonObjectCategory.put("last_sync_date", lastdateCat);
                    jsonObjectCategory.put("buyer_id", CommonUtilities
                            .getSellerId(getApplicationContext()));

                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                jsonCategoryArray.put(jsonObjectCategory);

            }


 JSONObject jsonCategory = buyerCategoryFunction
                            .getShopCategory(jsonCategoryArray.toString();

问题不是来自Web服务,因为它与HttpClient一起正常工作。 请帮我思考。

0 个答案:

没有答案