How to post JSON object to an api and receive raw text in Android using Volley
I'm new to Volley. I'm trying to change the deprecated HttpClient and HttpPost coding in my Android app with Volley coding. I learned JsonParsing from here and am able to implement it in my code. This code tells how to parse the response from the server and read the json object or array as the case may be.
Can anyone tell how to send a Json object to the server, where it gets saved to the database and then receive raw data. Solution or even a link to similar code will be appreciated. I've searched a lot but all in vain
I want to change the following code to its volley equivalent.
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());
}
}
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);
}
链接地址: http://www.djcxy.com/p/29514.html