How to send JSON data as body in POST request through HttpClient - mysql

I've a requirement. I have a working POST call ("http://localhost:8080/POSTAPI/table/testmaster/create"). I sent JSON data through postman and details got inserted into MySQL database. Now i'm trying to send the json data through apache httpcleint. but, it failed to insert into mysql database.
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/POSTAPI/table/testmaster/create");
JSONObject testmaster = new JSONObject();
testmaster.put("testRunId", testRunId);
testmaster.put("testClassName", className);
testmaster.put("testMethod", methodName);
testmaster.put("createdBy", "leela");
testmaster.put("createdDate", startDate);
testmaster.put("lastUpdatedBy", "raghu");
testmaster.put("lastUpdatedDate", endDate);
testmaster.put("attribute1", "methodName");
testmaster.put("attribute1Value",methodName );
testmaster.put("attribute2", "result");
testmaster.put("attribute2Value", successResult);
testmaster.put("attribute3", "Test Suite");
testmaster.put("attribute3Value", suiteName);
testmaster.put("attribute4", "test group");
testmaster.put("attribute4Value", TestGroup);
testmaster.put("attribute5", "dataprovider");
testmaster.put("attribute5Value", dataProvider);
StringEntity stringEntity = new StringEntity(testmaster.toString());
post.setEntity(stringEntity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out.println("Status: "+response.getStatusLine());
This is what i tried. if anybody have any idea of post operation through httpclient or any other alternative please let me know. Thanks in advance.

Use the following code :
private class postJsonData extends AsyncTask<Void, Integer, Boolean> {
ProgressDialog dialog;
String responseString = null;
private postJsonData() {
super();
dialog = new ProgressDialog(MainActivity.this);
this.dialog.setTitle("Please wait.");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected void onPreExecute() {
dialog.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
if (this.dialog.isShowing()) {
dialog.setProgress(progress[0]);
}
}
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(Void... params) {
Boolean result=false;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.2/android/jsonpost.php");
try {
JSONObject testmaster = new JSONObject();
try {
testmaster.put("testRunId", "1");
testmaster.put("testClassName", "className");
testmaster.put("testMethod", "methodName");
testmaster.put("createdBy", "leela");
testmaster.put("createdDate", "startDate");
} catch (JSONException e) {
e.printStackTrace();
}
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("json_string", testmaster.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
result = false;
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
result = false;
}
} catch (final ClientProtocolException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"ClientProtocolException : " + e.toString(),
Toast.LENGTH_LONG)
.show();
}
});
result = false;
} catch (final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"IOException : " + e.toString(),
Toast.LENGTH_LONG)
.show();
}
});
result = false;
}
return result;
}
#Override
protected void onPostExecute(final Boolean success) {
//progressBar.setVisibility(View.GONE);
if (dialog.isShowing()){
dialog.dismiss();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Response from Server: " + responseString ,
Toast.LENGTH_LONG)
.show();
}
});
if (success){
}else{
}
super.onPostExecute(success);
}
}
Here is my php code which accepts the json string and decode into array.
<?php
if (empty($_POST['json_string'])) {
echo "Empty json data";
exit;
}else{
$json_string = $_POST['json_string'];
}
$params = array();
$params = json_decode($json_string,true);
//echo $params['testClassName'];
var_dump($params);
?>

Related

I have a problem to use Volley. want to use POST method with some parameters and get Array type response but my response is not array type

I have a problem using Volley. want to use POST method with some parameters and get Array type response but my response is not an array type. Here, I share my request code and response.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
route = null;
route_spinner.setSelection(0);
check_in_date = null;
check_out_date = null;
adults = child = room = child1 = child2 = child3 = child4 = child5 = 0;
text_adults.setText("0 Adult");
text_child.setText("0 Child");
text_room.setText("0 Room");
layout_child.setVisibility(View.GONE);
in_date.setText("Add Date");
out_date.setText("Add Date");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
queue.add(postRequest);
when u use string request response you get will be string also.
you should turn that response to JsonArray , then get bojects from that JsonArray something like this :
if (response != null) {
JSONArray fetchlist = JSONArray(response);
for (int i=0 ; i<fetchlist .lenght ; i++) {
JSONObject obj = fetchlist.getJSONObject(i);
Int idd = obj.getInt("genderid");
I have solved this question in this way. Where hudx_Object and hudx_JSON is JSONObject
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest hudxconnect = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
hudx_Object = new JSONObject(response);
if (hudx_Object != null) {
hudx_JSON = hudx_Object.getJSONObject("response");
hudx_Object = new JSONObject(hudx_JSON.toString());
} else {
hudx_Object = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};

Send data with the JSONObject Volley library to the server with POST method

I want to send a JsonObject with below format to server by using Volley library.
{
"Email":"a#a.a",
"Password":"123456",
"ProveedorAcceso":"web",
"NivelAcceso":{
"Id": 1
},
"Estatus": {
"Id":1
} }
My code:
public void getData() {
StringRequest postRequest = new StringRequest(Request.Method.POST, urlLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.d(TAG, String.valueOf(jsonResponse));
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, String.valueOf(e));
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
try {
String responseBody = new String(volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
/**
dialogLoading.dismiss();
if (jsonObject.getInt("Codigo") == 400) {
onDialogErrorResponse();
}**/
} catch (JSONException e) {
//Handle a malformed json response
Log.d("Response", String.valueOf(e));
} catch (UnsupportedEncodingException error) {
Log.d("Response", String.valueOf(error));
}
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", edtEmail.getText().toString());
params.put("Password", edtPassword.getText().toString());
params.put("ProveedorAcceso", "web");
params.put("NivelAcceso", 1+"");
params.put("Estatus", 1+"");
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(postRequest);
DiskBasedCache cache = new DiskBasedCache(this.getCacheDir(), 500 * 1024 * 1024);
requestQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
requestQueue.start();
}
As the server does not receive the data correctly it throws me an error with reference to the data.
"Codigo":500,"Mensaje":"Object reference not set to an instance of an object."
I hope you can help me in this doubt, since I am very confused about it, thank you very much.

How to handle string response from php using android volley JsonObjectRequest [com.android.volley.ParseError: org.json.JSONException]?

Actually when we call API and send request in JSON format we are expecting response also come into JSON format. But here back end team sending me response in String format therefore my onErrorResponse () method get called. Here my status code is 200. But due to format of response not executed onResponse () method. So will you please help me to handle this? Might be I have to use CustomRequest here. Any suggestoin will be appreciated. Thanks
I have used volley json object request for accessing server.
My Request format is:
JSONObject json1 = new JSONObject();
try{
json1.put("","");
}catch(JSONException e){
e.printStackTrace();
}
new SampleJsonObjTask(MainActivity.this, json1);
and my SampleJsonObjTask class is:
public class SampleJsonObjTask {
public static ProgressDialog progress;
private static RequestQueue queue;
JSONObject main;
JsonObjectRequest req;
private MainActivity context;
public SampleJsonObjTask(MainActivity context, JSONObject main) {
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
this.context = context;
this.main = main;
ResponseTask();
}
private void ResponseTask() {
if (queue == null) {
queue = Volley.newRequestQueue(context);
}
req = new JsonObjectRequest(Request.Method.POST, "", main,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progress.dismiss();
Log.e("response","response--->"+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "error--->" + error.toString());
NetworkResponse response = error.networkResponse;
Log.e("statusCode","statusCode--->"+response.statusCode);
String json = null;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
break;
case 401:
json = new String(response.data);
break;
case 502:
json = new String(response.data);
break;
case 200:
json = new String(response.data);
break;
}
progress.dismiss();
}
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1f));
queue.add(req);
}}
Here the Response coming like string format that is Value OK, please help me to how to get the string response which i have mentioned below.
com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject
How to get this string response by using json object request.
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.cancel();
Log.d("response", response);
}catch (Exception e){
volleyResponseCallBack.onFailure("Something went wrong!");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
dialog.cancel();
if (volleyError instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (volleyError instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (volleyError instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
if (!(message == null)) {
Log.d("response", message);
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);

json parsing using uri for listview in android

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...
Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Get notification of HttpWebResponse

I have a ComClass for windows phone 8 that post and read data from a url.
public class ComClass
{
private string _url = """;
private string _postdata = "";
public Boolean data_received;
public string data;
public ComClass(string url, string data2send)
{
_url = url;
_postdata = data2send;
}
public void Send()
{
data_received = false;
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create(_url);
request.ContentType = "application/json;charset=UTF-8";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asyncResult);
byte[] byteArray = Encoding.UTF8.GetBytes(_postdata.ToString());
postStream.Write(byteArray, 0, _postdata.Length);
postStream.Dispose();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
data = streamRead.ReadToEnd();
data_received = true;
streamResponse.Dispose();
streamRead.Dispose();
response.Dispose();
}
catch (WebException ex)
{
data = ex.Message;
data_received = false;
//using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
//{
// //Debug.WriteLine("Exception output : " + ex);
//}
}
}
}
The class works fine. My problem is that i want somehow to get notified that i have a response. eg
ComClass ccc = null;
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ccc = new ComClass("url", "somedata");
ccc.Send();
//while (ccc.data_received == false)
//{ }
string itemdata = ccc.data;
//do something with itemdata...
}
catch (Exception ee)
{
}
}
I know that i must use await or delegates but i am stuck...