0

send json array object as a parameter to php service from android I've a json object with many string data and a jsonarray data

**ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
    HttpResponse httpResponse = null;

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONArray product_array = null;
        /*
         * namevaluepair.add(new BasicNameValuePair("val1",val1));
         * namevaluepair.add(new BasicNameValuePair("val2",val2));
         */

        try {
            nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair("n", jsonParams
                    .getString("n")));
            nameValuePair.add(new BasicNameValuePair("e", jsonParams
                    .getString("e")));
            nameValuePair.add(new BasicNameValuePair("p", jsonParams
                    .getString("p")));
            nameValuePair.add(new BasicNameValuePair("a", jsonParams
                    .getString("a")));
            nameValuePair.add(new BasicNameValuePair("t", jsonParams
                    .getString("t")));
            nameValuePair.add(new BasicNameValuePair("m", jsonParams
                    .getString("m")));
            product_array = jsonParams.getJSONArray("pj");
            Log.i(TAG + "PPPPJJJ", product_array.toString());
        //  nameValuePair.add(new BasicNameValuePair("pj", product_array
                //  .toString()));
        } catch (Exception e) {
            Log.e(TAG, "2:" + e.getMessage());
        }

        String enc_url = URLEncoder.encode(url);
        HttpPost httpPost = new HttpPost(enc_url);
        httpPost.addHeader("accept", "application/json");
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        httpResponse = httpClient.execute(httpPost);


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }**

but it is not forwarding the json array to server,server php file is not receiving that array data, but working fine with browser So I assume problem is in my code.

Error that I am getting while executing the code as below.

07-08 23:37:56.504: W/System.err(3219): java.lang.IllegalStateException: Target host must not be null, or set in parameters.
07-08 23:37:56.514: W/System.err(3219):     at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:572)
07-08 23:37:56.514: W/System.err(3219):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:292)
07-08 23:37:56.514: W/System.err(3219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-08 23:37:56.525: W/System.err(3219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-08 23:37:56.525: W/System.err(3219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-08 23:37:56.525: W/System.err(3219):     at com.nufame.nufamemotel.utils.ConnectToNetwork.posthttp(ConnectToNetwork.java:200)
07-08 23:37:56.525: W/System.err(3219):     at com.nufame.nufamemotel.utils.ConnectToNetwork.getData(ConnectToNetwork.java:67)
07-08 23:37:56.534: W/System.err(3219):     at com.nufame.nufamemotel.utils.QueryServer.doInBackground(QueryServer.java:20)
07-08 23:37:56.534: W/System.err(3219):     at com.nufame.nufamemotel.utils.QueryServer.doInBackground(QueryServer.java:1)
07-08 23:37:56.534: W/System.err(3219):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-08 23:37:56.534: W/System.err(3219):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
07-08 23:37:56.544: W/System.err(3219):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
07-08 23:37:56.544: W/System.err(3219):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
07-08 23:37:56.544: W/System.err(3219):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
07-08 23:37:56.544: W/System.err(3219):     at java.lang.Thread.run(Thread.java:1019)
07-08 23:37:56.544: E/...Error occured ....response(3219): java.lang.IllegalStateException: Target host must not be null, or set in parameters.
07-08 23:37:56.544: I/OrderHandler(3219): exception
07-08 23:37:56.544: W/System.err(3219): org.json.JSONException: Value exception of type java.lang.String cannot be converted to JSONObject
07-08 23:37:56.564: W/System.err(3219):     at org.json.JSON.typeMismatch(JSON.java:107)
07-08 23:37:56.564: W/System.err(3219):     at org.json.JSONObject.<init>(JSONObject.java:158)
07-08 23:37:56.564: W/System.err(3219):     at org.json.JSONObject.<init>(JSONObject.java:171)
07-08 23:37:56.564: W/System.err(3219):     at com.nufame.nufamemotel.handler.OrderHandler$1.onPostExecute(OrderHandler.java:108)
07-08 23:37:56.564: W/System.err(3219):     at com.nufame.nufamemotel.handler.OrderHandler$1.onPostExecute(OrderHandler.java:1)
07-08 23:37:56.564: W/System.err(3219):     at android.os.AsyncTask.finish(AsyncTask.java:417)
07-08 23:37:56.564: W/System.err(3219):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-08 23:37:56.564: W/System.err(3219):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-08 23:37:56.574: W/System.err(3219):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-08 23:37:56.574: W/System.err(3219):     at android.os.Looper.loop(Looper.java:123)
07-08 23:37:56.574: W/System.err(3219):     at android.app.ActivityThread.main(ActivityThread.java:3683)
07-08 23:37:56.574: W/System.err(3219):     at java.lang.reflect.Method.invokeNative(Native Method)
07-08 23:37:56.574: W/System.err(3219):     at java.lang.reflect.Method.invoke(Method.java:507)
07-08 23:37:56.574: W/System.err(3219):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-08 23:37:56.584: W/System.err(3219):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-08 23:37:56.584: W/System.err(3219):     at dalvik.system.NativeStart.main(Native Method)
3
  • you want to send that data to server database?? Commented Aug 5, 2013 at 12:26
  • try this <stackoverflow.com/questions/17991347/…> Commented Aug 5, 2013 at 12:32
  • yea i'm traying to send those data to server Commented Aug 5, 2013 at 12:42

3 Answers 3

3

You can use my droidQuery library to send this very easily:

$.ajax(new AjaxOptions().url("http://www.example.com")//switch with real URL
                        .type("POST")
                        .dataType("json")
                        .data(jsonParams)//your JSON Object
                        .context(this)
                        .success(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                //if you are expecting a JSONObject:
                                JSONObject response = (JSONObject) params[0];
                                //TODO: handle response
                            }
                        })
                        .error(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                AjaxError error = (AjaxError) params[0];
                                $.toast(error.status + ": " + error.reason, Toast.LENGTH_LONG);
                                //retry once
                                $.ajax(error.request, error.options.error($.noop()));
                            }
                        }));
Sign up to request clarification or add additional context in comments.

Comments

1

This is how I believe it should be done:

URL url = new URL("//ip of your PHP function on your web server");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(URLEncoder.encode("005", "UTF-8"));
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("item 1", "value 1");
//Add other pairs here, as you are doing
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
    response.append(line);
    response.append('\n');
}
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println(response.toString());
}
else {                                    
    System.out.println("Incorrect response code");
}
br.close();
urlConnection.disconnect();

This code allows you to send the JSON object, then get the response using the InputStream and BufferedReader. Hope this is helpful!

3 Comments

mattpic > I've many other parameters which are just string and only one parameter I'm supposed to pass as json array
Now it is working i solved the issue, String enc_url = URLEncoder.encode(url); HttpPost httpPost = new HttpPost(enc_url); httpPost.addHeader("accept", "application/json");
I'm glad I could help. If this helped you find the solution, please mark the answer correct
1
JSONObject j = new JSONObject(); try {
        j.put("n", jsonParams
                .getString("n"));
        j.put("e", jsonParams
                .getString("e"));
        j.put("p", jsonParams
                .getString("p"));
        j.put("e", jsonParams
                .getString("p"));
          j.put("a", jsonParams
                .getString("a"));
        j.put("t", jsonParams
                .getString("t"));
        j.put("m", jsonParams
                .getString("m"));
        product_array = jsonParams.getJSONArray("pj");
        Log.i(TAG + "PPPPJJJ", product_array.toString());

        j.put("array", product_array);
    } catch (Exception e) {
        Log.e(TAG, "2:" + e.getMessage());
    }

    String enc_url = URLEncoder.encode(url);
    HttpPost httpPost = new HttpPost(enc_url);
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(new UrlEncodedFormEntity(j));
    httpResponse = httpClient.execute(httpPost);


} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}**

also refer here Android JSON HttpClient to send data to PHP server with HttpResponse

1 Comment

I've solved the issue it works fine when i removed the header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.