0

I need to send a String to my Web Service and I have doubts about how to send string using HttpURLConnection.

Obs: in String "result" I have something like:

 {"sex":"Famale","nome":"Larissa Aparecida Nogueira","convenios":[{"convenio":2,"tipo":"Principal","number":"44551-1456-6678-3344"}],"user":"lari.ap","email":"[email protected]","cell":"(19)98167-5569"}

following is my code:

   public UsuerService(Context context, String result) {
       this.progressDialog = new ProgressDialog(context);
       this.context = context;
       this.result = result;
   }

  @Override
   protected String doInBackground(String... params) {

        String responseString = "";
        try {
             URL url = new URL(Constants.USUARIO + "/createUsuario");
             HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
             httpURLConnection.setRequestMethod("POST");


             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
             String inputLine;
             StringBuilder response = new StringBuilder();

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

            result = response.toString();
            bufferedReader.close();
           } catch (Exception e) {
            Log.d("InputStream", e.getMessage());
        }

         return null;
   }

I have a Class that picks up my data and parses it to JsonObject. I need to understand how to send my object.toString() for web service using HttpURLConnection.

following is the code:

 public String parserUsuarioJson(){

    JSONObject object = new JSONObject();

    try {
        object.put(Constants.KEY_NAME, mUsuario.getNome());
        object.put(Constants.KEY_EMAIL, mUsuario.getEmail());
        object.put(Constants.KEY_USER, mUsuario.getUser());
        object.put(Constants.KEY_PASS, mUsuario.getSenha());
        object.put(Constants.KEY_SEX, mUsuario.getSexo());
        object.put(Constants.KEY_CELLPHONE, mUsuario.getCelular());

        JSONArray array = new JSONArray();

        for(int i = 0; i < mUsuario.getUsuarioConvenios().size() ; i++){
            JSONObject convenio = new JSONObject();

            convenio.put(Constants.KEY_CONVENIO, mUsuario.getUsuarioConvenios().get(i).getConvenio().getId());
            convenio.put(Constants.KEY_NUMBER, mUsuario.getUsuarioConvenios().get(i).getNumero());
            convenio.put(Constants.KEY_TYPE, mUsuario.getUsuarioConvenios().get(i).getTipo());

            array.put(convenio);
        }
        object.put(Constants.KEY_CONVENIOS, array);
    } catch (JSONException e) {
        Log.e("Register", e.getMessage());
    }

    return object.toString();

}

Thanks in advance. :)

2
  • Use volley for all NetworkCalls in android. Its Google library and very easy to use. developer.android.com/training/volley/index.html Commented Oct 27, 2015 at 17:42
  • 1
    You should pseudonymize the information, as you've just posted some womans cell phone number on the internet! Commented Oct 27, 2015 at 19:20

3 Answers 3

1

Use NameValuePairList to send the data.

Try something like this...

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.USUARIO + "/createUsuario");

try { 
        // Add your key-value pair here
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("sex", "female"));
        nameValuePairs.add(new BasicNameValuePair("nome", "Larissa Aparecida Nogueira"));
        // set all other key-value pairs

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block 
    } catch (IOException e) {
        // TODO Auto-generated catch block 
    } 

For Sending json Object over network using http post.

pass the json string here

 StringEntity se = new StringEntity(object.toString());
 httpost.setEntity(se);
 httpost.setHeader("Accept", "application/json");
 httpost.setHeader("Content-type", "application/json");
 HttpResponse response = httpclient.execute(httpost);

Don't forget to catch the exception.

Sending json Object using httpurlConnection...

try {
  //constants
  URL url = new URL(Constants.USUARIO + "/createUsuario");
  String yourJsonString = object.toString();

  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setRequestMethod("POST");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setFixedLengthStreamingMode(yourJsonString.getBytes().length);

  conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
  conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

  conn.connect();

  OutputStream os = new BufferedOutputStream(conn.getOutputStream());
  os.write(yourJsonString.getBytes());

  os.flush();

  InputStream is = conn.getInputStream();
} finally {  
  //clean up
  os.close();
  is.close();
  conn.disconnect();
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hello Ritesh. Thank you for you response, but I have an class that parser my data to Json Object. I update my question with this class. I need understand how to I send object.toString() for my web service using httpurlconnection. thanks
HttpClient or HttpURLConnection?? I cannot find HttpClient
thats because HttpClient api is not in your project. Have tried using HttpURLConnection?
yes. I'm using HttpURLConnection but I think that HTTPURLConnection not use StringEntitiy se = new StringEntity(object.toString());
how to use httpost.setEntity(se); in HttpUrlConnection? do you know?
|
0
  @Override
  protected String doInBackground(String... params) {
    try {

        URL url = new URL(Constants.USUARIO + "/createUsuario");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setFixedLengthStreamingMode(result.getBytes().length);

        httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

        httpURLConnection.connect();

        OutputStream os = new BufferedOutputStream(httpURLConnection.getOutputStream());
        os.write(result.getBytes());
        os.flush();

        os = httpURLConnection.getOutputStream();

        os.close();
        httpURLConnection.disconnect();

    } catch (Exception e) {
        Log.d("InputStream", e.getMessage());
    }

1 Comment

what is "result"? It has been used twice
0

As I am getting ,You want to send a String to a Webservice . I am giving you a sample code here ,where I am sending some string values to a webservice . It's working code `

    private class BackgroundOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) 
            //Your network connection code should be here .
            String response = postCall("Put your WebService url here");
            return response ;
        }

        @Override
        protected void onPostExecute(String result) {
            //Print your response here .
            Log.d("Post Response",result);

        }

        @Override
        protected void onPreExecute() {}

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

        public static String postCall(String uri) {
        String result ="";
        try {
            //Connect
            HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
            //Write
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
            writer.write(parserUsuarioJson());
            writer.close();
            outputStream.close();

            //Read
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

Now you can call above from from your activity's onCreate() function using below code .

new BackgroundOperation().execute("");

Note : Don't forget to mention below permission in your manifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 

Note : Make sure

1 . parserUsuarioJson() is returning proper json string .

2 . Your webservice is working .

4 Comments

Hello Android Dev. Thank you for you response, but I have an class that parser my data to Json Object. I update my question with this class.
I need understant how to I send object.toString(); for my web service using httpURLConnection. thanks :)
I have edited the answer to meet your requirement . It will work definitely if your parserUsuario() is returning proper json and your webservice is working .
Response from Webservice will be printed in LogCat . So check your Logcat after executing new BackgroundOperation().execute("");

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.