使用volley android将数据发送到asp.net服务器

时间:2018-02-24 10:58:54

标签: android android-volley

我想从我的Android应用程序向服务器发送数据我搜索了关于凌空并编写了下面的代码,但它无法正常工作你能帮我解决一下吗?

我使用地图获取数据然后我提取密钥并将它们放到字符串数组中:

keys=new String[data.size()];
data.keySet().toArray(keys); 

之后,我提出这样的要求:

for (int i=0;i<data.size();i++) {
    requestJsonObject.put(keys[i], data.get(keys[i])); 
}

以下是完整的代码:

public  class  ApiPostData {

    private static final String TAG = "PostData";
    private String url;
    private HashMap<String,String> data=new HashMap<>();

    String[] keys;

    public String getUrl() {
        return url;
    }

    public ApiPostData setData(HashMap<String, String> data) {
        this.data = data;
        return this;
    }

    public ApiPostData setUrl(String url) {
        this.url = url;
        return this;
    }

    public void PostData(final OnSetSettingComplete onSetSettingComplete) {
        JSONObject requestJsonObject = new JSONObject();
        try {
            keys=new String[data.size()];
            data.keySet().toArray(keys);  
            for (int i=0;i < data.size(); i++) {
                requestJsonObject.put(keys[i], data.get(keys[i])); 
            }
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestJsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        int success = response.getInt("statusCode");
                        onSetSettingComplete.onResponse(success);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

            request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            Volley.newRequestQueue(G.context).add(request);

        } catch (JSONException e) {
            Log.e(TAG, "EpostData: " + e.toString());
        }
    }

    public interface OnSetSettingComplete {
        void onResponse(int success);
    }

}

1 个答案:

答案 0 :(得分:0)

建议使用okhttp

OkHttpClient client = new OkHttpClient();
RequestBody body = new     FormEncodingBuilder().add("key1","value1").add("key1","value2").add("key3","valu    e3").build();
Request request = new Request.Builder()
    .url("URL HERE")
        .addHeader("Some Headers Here", "Header Values Here")
        .addHeader("Some Headers Here", "Header Values Here")
        .post(body)
        .build();
Response response = client.newCall(request).execute();