简体   繁体   English

如何将发布请求发送到Web服务?

[英]How do i send post request to a webservice?

I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. 我遵循这篇文章http://hmkcode.com/android-send-json-data-to-server/,并且某些功能已弃用。 I like to understand how I send an information to a web service. 我想了解如何将信息发送到Web服务。

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. 我这个网址http://hmkcode.appspot.com/post-json/index.html是要检查的。 I like a help to get it ok. 我需要帮助来使它正常运行。

Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. 不幸的是,如果不使用第三方库,则在Android中发送HTTP请求是很痛苦的。 Fortunately retrofit is awesome and is very widely used. 幸运的是, 翻新很棒,并且得到了广泛的应用。 There are a lot tutorials for it, you might try this one for example. 有很多教程,您可以尝试例如一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM