如何使用Volly发布数据并接收JSON对象

时间:2018-02-11 21:07:20

标签: android json android-volley

我想将一个int发布到https地址并将3个JSON对象传递给文本视图,但我无法获得JSON结果。我试过在onResponse中使用方法,但它没有用。如何POST一个整数并将一些JSON对象解析为文本视图?我是Android开发的初学者,我不知道如何解决这个问题。 有什么问题?请帮忙

    if(isNetworkAvailable()){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://example.com/api";
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            Log.d("Response", response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            alertUserAboutError();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        mStoreName.setText("Error");
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("category_id", "28");

                return params;
            }
        };

        queue.add(postRequest);

    }
        Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show(); }
private void updateDisplay() {
    mStoreName.setText(mStoreDetails.getStoreName());
    mInstagram.setText(mStoreDetails.getInstagram());
    mTelegram.setText(mStoreDetails.getTelegram());

}

private StoreDetails getStoreDetails(String jsonData) throws JSONException {
    JSONObject JSONRequest = new JSONObject(jsonData);

    StoreDetails storeDetails = new StoreDetails();
    storeDetails.setStoreName(JSONRequest.getString("store_name"));
    storeDetails.setInstagram(JSONRequest.getString("instagram"));
    storeDetails.setTelegram(JSONRequest.getString("telegram"));

    return storeDetails;
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void alertUserAboutError() {
    AlertDialogFragment dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(), "error_dialog");
}

1 个答案:

答案 0 :(得分:0)

这对我有用。使用stringrequest将发布数据放入请求中。在onResponse被调用后,我从字符串创建一个JSON-Object:

public void doServerRequest(final Context context, final String url, final Map<String,String> postParameters, final HashMap<String,String> getParameters, final OnFinishTaskListener<String, JSONObject> listener){
    Log.d(TAG,"Start new server request (" + url + ")");
    StringRequest request = new StringRequest(Request.Method.POST, addParametersToUrl(url, getParameters), new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response);
            try {
                JSONObject json = new JSONObject(response);
                if (json.getInt(CODE_TAG) == 0){
                    listener.getResult(SUCCESS_TAG, json);
                } else {
                    listener.getResult(ERROR_TAG, null);
                }
            } catch (Exception e){
                e.printStackTrace();
                listener.getResult(ERROR_TAG, null);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            listener.getResult(ERROR_TAG, null);
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            if(postParameters == null){
                return new HashMap<String, String>();
            }
            return postParameters;
        }
    };
    requestQueue.add(request);
}

这会将get-Paramters添加到URL(如果存在):

private String addParametersToUrl(String url, HashMap<String,String> getParameters){
    if(getParameters == null || getParameters.size() == 0){
        return url;
    }
    Log.d(TAG,"Preparing URL: "+url);
    StringBuilder stringBuilder = new StringBuilder(url);
    stringBuilder.append("?");
    int i = 0;
    for (String key : getParameters.keySet()) {
        if(i>0) stringBuilder.append("&");
        stringBuilder.append(key).append("=").append(getParameters.get(key));
        i++;
    }
    url = stringBuilder.toString();
    Log.d(TAG,"Prepared URL: "+url);
    return url;
}

我使用这个监听器接口:

public interface OnFinishTaskListener<S,J> {
    public void getResult(S string, J json);
}