0

I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. I like to understand how I send an information to a web service.

I try to update the post but i got some mistake.. I know my code has some mistake My code is:

enter code here
package com.example.paulo.myapp.POST;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.paulo.myapp.R;
import com.facebook.internal.BundleJSONConverter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class Post_Dados extends AppCompatActivity implements View.OnClickListener {

    TextView isconected;
    EditText customer, pais, twitter;
    Button btn_enviar;
    String person, country, tw;
    static Dados dados;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post__dados);

        /* recupera as views */

        isconected =  (TextView) findViewById(R.id.conected);
        customer = (EditText) findViewById(R.id.customer);
        pais = (EditText) findViewById(R.id.pais);
        twitter =  (EditText) findViewById(R.id.twitter);
        btn_enviar = (Button) findViewById(R.id.sendWS);

        /* checa se está conectado */

        if (isConnected()) {

            isconected.setText("Conectado !!!!");
        }

        else {

            isconected.setText("Não conectado!!!");
        }


         /* click do botão */
        btn_enviar.setOnClickListener(this);

    }

    private boolean isConnected() {

        ConnectivityManager cm = (ConnectivityManager ) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if ( info != null && info.isConnected()){
            return true;
        }
        else {  return false; }    }

    @Override
    public void onClick(View view) {

        String c = customer.getText().toString();
        String p = pais.getText().toString();
        String t = twitter.getText().toString();

                if ( c.equals("") || p.equals("") || t.equals("") )

                {

            Toast.makeText(getBaseContext(), "Preenche os campos os dados!", Toast.LENGTH_LONG).show();


                    }

        else{

            new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
        }


    }



      /*metodo de conexao */

    private static String POST(String url, String person) throws IOException, JSONException {

        InputStream inputStream = null;
        String result = "";

        try{

            /* 1.  cria o httpClient */
            URL endWeb = new URL(url);
            HttpURLConnection con = (HttpURLConnection) endWeb.openConnection();

            // 2. configurando o POST

            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setUseCaches(false);
            con.setRequestProperty("Accept", "application/json");

            //3. define enviar e receber
            con.setDoOutput(true);
            con.setDoInput(true);

            //4.faz a conexao
            con.connect();

            //5. Objeto json

            String json = " ";
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name",dados.getNome());
            jsonObject.accumulate("country", dados.getEmail());
            jsonObject.accumulate("twitter", dados.getTwitter());


            //6.connverte json to json string

            json = jsonObject.toString();

            // Escreve o objeto JSON usando o OutputStream da requisição:
            OutputStream outputStream = con.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
        }

        catch (Exception e){
            throw e;
        }

        return  "ok";
    }


    private class HttpAsyncTask extends  AsyncTask<String, Void, String>{
        String result;
        @Override
        protected String doInBackground(String... urls) {

            dados = new Dados(person.toString(), country.toString(), tw.toString());

            try {
              result =  POST(urls[0], person);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        return  result;
        }


        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Dados enviados!", Toast.LENGTH_LONG).show();
        }
    }

}

I this url http://hmkcode.appspot.com/post-json/index.html is to check it´s ok. I like a help to get it ok.

  • Your question could be easily solved with a far smaller piece of code. I prefer not to work through all this code. also: add language tags to target the right audience. – Patrick Artner Nov 12 '17 at 14:39

1 Answers1

0

Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. Fortunately retrofit is awesome and is very widely used. There are a lot tutorials for it, you might try this one for example.

Casper
  • 471
  • 7
  • 12