-1

I am new to Android development and I observed that HttpClient has been deprecated in API 22 .then I found that HttpUrlConnection is supported by Android.I searched for many tutorials but I am not able to find solution for sending post parameters in JSON format to a PHP script . Guide me the way to solve that problem.

Krish
  • 3
  • 2
  • [duplicate](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) – AKroell Jun 02 '15 at 09:17

3 Answers3

1

You can used the following asynchronous method .

    public class BackgroundActivity extends AsyncTask<String,Void,String> {
    @Override
    protected String doInBackground(String... arg0) {



            try {
                HttpParams httpParams = new BasicHttpParams();
                //connection timeout after 5 sec
                HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
                HttpConnectionParams.setSoTimeout(httpParams, 5000);

                HttpClient httpclient = new DefaultHttpClient(httpParams );
                HttpPost httppost = new HttpPost(link);
                JSONObject json = new JSONObject();

                // JSON data:

                    json.put("name", argo);
                    json.put("address", arg1);
                    json.put("Number", arg2);



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

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

                // Execute HTTP Post Request
              //  System.out.print(json);
                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);
                            break;
                        }
                    } catch (IOException e) {

                    } finally {
                        try {
                            is.close();
                        } catch (IOException e) {

                        }
                    }
                    result = sb.toString();

                }

                return result;
            } catch (ClientProtocolException e) {
                return "Exception";
            }

            catch (JSONException e) {
                return"Exception";
            } catch (IOException e) {

                return "Exception";
            }



    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected void onPostExecute (String result){


    }


    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

}
Heriberto Lugo
  • 589
  • 7
  • 19
Suresh A
  • 1,178
  • 2
  • 10
  • 21
0

Here is the implementation:

/**
 * Created by Skynet on 20/5/15.
 */
public class UniversalHttpUrlConnection {

        public static String sendPost(String url, String params) throws Exception {

            String USER_AGENT = "Mozilla/5.0";
            URL obj = new URL(url);

            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            /* Send post request */
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(params);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + params);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            Log.d("rvsp", response.toString());

            return response.toString();

            }
}

And here is how to call it:

 String postdata = "jArr=" + fbArray + "&Key=" + getencryptkey() + "&phoneType=Android" + "&flag=" + params[0];
 response = UniversalHttpUrlConnection.sendPost(getResources().getString(R.string.reg_register_url), postdata);

Edit:

As per OP's request, params in JSON format:

private void postJSON(String myurl) throws IOException {
        java.util.Date date= new java.util.Date();
        Timestamp timestamp = (new Timestamp(date.getTime()));
        try {
            JSONObject parameters = new JSONObject();
            parameters.put("timestamp",timestamp);
            parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
            parameters.put("type", "Android");
            parameters.put("mail", "xyz@gmail.com");
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //  conn.setReadTimeout(10000 /* milliseconds *///);
            //  conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty( "Content-Type", "application/json" );
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response.toString());

        }catch (Exception exception) {
            System.out.println("Exception: "+exception);
        }
    }
Skynet
  • 7,820
  • 5
  • 44
  • 80
  • how to add parameters and why did u use useragent header?? – Krish Jun 02 '15 at 09:21
  • The HTTP specification states that all clients are supposed to sent User-Agent headers. It however, does not state that they should identify the client in the manner a server wishes to. Android therefore complies with the specification. – Skynet Jun 02 '15 at 09:30
  • Look at the last and second last line in the code above, that is how you send params. In my answer, the Post Params would be `jArr` `fbArray` `phoneType` and `flag` use the `&` operator to separate. – Skynet Jun 02 '15 at 09:32
  • can u give me another way to add post parametrs into JSON format and then send to the PHP script for decoding – Krish Jun 02 '15 at 11:12
  • The above will be received as arrays, I will update the code for JSON too. – Skynet Jun 02 '15 at 12:09
  • Updated in the answers Edit section. Do check! – Skynet Jun 02 '15 at 12:11
  • Thanx for the answer. – Krish Jun 02 '15 at 14:47
  • No the data is neither posting in database and no response also from the server – Krish Jun 03 '15 at 05:27
0

Although it might be a good idea to do it with HttpURLConnection once or twice to learn about the Input- and Outputstream but I would definitely recommend a library such as okhttp or retrofit because it's much less painful longterm.

anstaendig
  • 795
  • 5
  • 13