如何将JSON对象发布到api并使用Volley在Android中接收原始文本

时间:2017-11-29 05:10:36

标签: android json post android-volley

我是Volley的新手。我尝试使用Volley编码在我的Android应用中更改已弃用的HttpClient和HttpPost编码。 我从Bostock recommends学习了JsonParsing,并且能够在我的代码中实现它。 此代码告诉如何从服务器解析响应并根据具体情况读取json对象或数组。

任何人都可以告诉如何将Json对象发送到服务器,然后将其保存到数据库然后接收原始数据。解决方案甚至是类似代码的链接将不胜感激。我搜索了很多但都是徒劳的

我想将以下代码更改为等效的。

private void saveToSite() {
    try{
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("http://clctn.mysite.com/data/checklog.php");
        JSONObject json = new JSONObject();

        json.put("name", ed_name.getText().toString());
        json.put("address", ed_address.getText().toString());
        json.put("contact", ed_contact.getText().toString());

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }catch (ClientProtocolException e) {
        Log.e("cpe1 ", e.toString());
    } catch (IOException e) {
        Log.e("ioe1 ", e.toString());
    } catch (JSONException e){
        Log.e("jsonex ", e.toString());
    }
}

1 个答案:

答案 0 :(得分:0)

StringRequest request = new StringRequest(Request.Method.POST, 
StaticVeriable.GET_PHOTOS, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            params.put("parameter1", ""+yourjsonObject.toString(););

            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(request);
}