1

Background

I have the following functions, both do the same thing that is POST to a php page:

private void parse(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", mail);


            //System.out.println("PARAMS"+parameters.toString());


            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);
        }
    }

In the above I am only sending a single string to the php server at:

writer.write(parameters.toString());

Now I have this function:

InputStream ins = null;
    String result = null; 
    public void postJSON(String url){

        DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams()); 
        HttpPost httppost = new HttpPost(url);
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try{
            JSONArray json = (makeJSON());
            //  System.out.println("Arrays"+Arrays.asList(json).toString()); 
            //  System.out.println(("simple"+json));

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("timestamp", "t"));
            nameValuePairs.add(new BasicNameValuePair("mail", "t"));
            nameValuePairs.add(new BasicNameValuePair("type", "t"));
            nameValuePairs.add(new BasicNameValuePair("jsonArray", Arrays.asList(json).toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse resp = http.execute(httppost); 
            HttpEntity entity = resp.getEntity();
            ins = entity.getContent(); 
            BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8); 
            StringBuilder sb = new StringBuilder(); 
            String line = null; 
            while((line = bufread.readLine()) != null){
                sb.append(line +"\n"); 
            }
            result = sb.toString(); 
            System.out.println(result);
            /*  if(result.equalsIgnoreCase("There is no update in database")){


            }else{
                //  System.out.println(result);
                readAndParseJSON(result);
            } */


        }catch (Exception e){

            //  System.out.println("Error: "+e);

        }finally{
            try{
                if(ins != null){
                    ins.close();
                }
            }catch(Exception smash){
                System.out.println("Squish: "+smash); 
            }
        }
        //  return  result; 

    }

In the above I am sending name value pairs which I can fetch at the php side based on their names.

As HttpUrlConnection is the suggested way to go in for Android how can I modify the first function to cater for name value pairs. I tried looking online but it just confuses me.

I am also very confused at this line:

conn.setRequestProperty( "Content-Type", "application/json" );

What does the above infer?

and these two:

httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Community
  • 1
  • 1
User3
  • 2,105
  • 6
  • 35
  • 73
  • "application/json" is the header required for the POST you are making if the data you are sending is in the form of json – Ichigo Kurosaki Jan 21 '15 at 07:42
  • What does "Accept" refer to? and why do I set it twice? Doesn't the second time override the first time? Also in my case I am sending nameValue Pairs of which one is of the form JSON and that to in string format. Really confusing. – User3 Jan 21 '15 at 07:48
  • a=b&c=d are name value pairs where your server code can retrieve by name to get the value. corresponds to "application/x-www-form-urlencoded" {"a":"b", "c":"d"} is a single value string that server code needs to first parse/serialize to read the values. corresponds to "application/json" Accordingly you need to set the Header based on what data you want to send and the type of behavior you need. A really comprehensive explanation : "http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests/2793153#2793153" – Gyan Jan 21 '15 at 08:16

0 Answers0