简体   繁体   English

如何将 json 对象从我的 android 应用程序发送到服务器

[英]How To Send json Object to the server from my android app

I'm at a bit of a loss as to how to send a json object from my android application to the database我对如何将json对象从我的 android 应用程序发送到数据库有点不知所措

As I am new to this I'm not too sure where I've gone wrong, I've pulled the data from the XML and I have no clue how to then post the object to our server.由于我是新手,我不太确定我哪里出错了,我已经从XML提取了数据,但我不知道如何将对象发布到我们的服务器。

any advice would be really appreciated任何建议将不胜感激

 package mmu.tom.linkedviewproject;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.IOException;
    
    /**
     * Created by Tom on 12/02/2016.
     */
    public class DeviceDetailsActivity extends AppCompatActivity {

    private EditText address;
    private EditText name;
    private EditText manufacturer;
    private EditText location;
    private EditText type;
    private EditText deviceID;


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

        ImageButton button1 = (ImageButton) findViewById(R.id.image_button_back);
        button1.setOnClickListener(new View.OnClickListener() {
            Class ourClass;

            public void onClick(View v) {

                Intent intent = new Intent(DeviceDetailsActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });


        Button submitButton = (Button) findViewById(R.id.submit_button);

        submitButton.setOnClickListener(new View.OnClickListener() {
            Class ourClass;

            public void onClick(View v) {

                sendDeviceDetails();
            }
        });

        setContentView(R.layout.activity_device_details);

        this.address = (EditText) this.findViewById(R.id.edit_address);
        this.name = (EditText) this.findViewById(R.id.edit_name);
        this.manufacturer = (EditText) this.findViewById(R.id.edit_manufacturer);
        this.location = (EditText) this.findViewById(R.id.edit_location);
        this.type = (EditText) this.findViewById(R.id.edit_type);
        this.deviceID = (EditText) this.findViewById(R.id.edit_device_id);

    }




        protected void onPostExecute(JSONArray jsonArray) {

            try
            {
                JSONObject device = jsonArray.getJSONObject(0);

                name.setText(device.getString("name"));
                address.setText(device.getString("address"));
                location.setText(device.getString("location"));
                manufacturer.setText(device.getString("manufacturer"));
                type.setText(device.getString("type"));
            }
            catch(Exception e){
                e.printStackTrace();
            }




        }

    public JSONArray sendDeviceDetails() {
        // URL for getting all customers


        String url = "http://IP-ADDRESS:8080/IOTProjectServer/registerDevice?";

        // Get HttpResponse Object from url.
        // Get HttpEntity from Http Response Object

        HttpEntity httpEntity = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

            httpEntity = httpResponse.getEntity();


        } catch (ClientProtocolException e) {

            // Signals error in http protocol
            e.printStackTrace();

            //Log Errors Here


        } catch (IOException e) {
            e.printStackTrace();
        }


        // Convert HttpEntity into JSON Array
        JSONArray jsonArray = null;
        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);
                Log.e("Entity Response  : ", entityResponse);

                jsonArray = new JSONArray(entityResponse);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return jsonArray;


    }


}


   

You need to be using an AsyncTask class to communicate with your server.您需要使用AsyncTask类与您的服务器进行通信。 Something like this:像这样的东西:

This is in your onCreate method.这是在您的onCreate方法中。

Button submitButton = (Button) findViewById(R.id.submit_button);

submitButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        JSONObject postData = new JSONObject();
        try {
            postData.put("name", name.getText().toString());
            postData.put("address", address.getText().toString());
            postData.put("manufacturer", manufacturer.getText().toString());
            postData.put("location", location.getText().toString());
            postData.put("type", type.getText().toString());
            postData.put("deviceID", deviceID.getText().toString());

            new SendDeviceDetails().execute("http://52.88.194.67:8080/IOTProjectServer/registerDevice", postData.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

This is a new class within you activity class.这是您活动课程中的一个新课程。

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

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

        String data = "";

        HttpURLConnection httpURLConnection = null;
        try {

            httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes("PostData=" + params[1]);
            wr.flush();
            wr.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
    }
}

The line: httpURLConnection.setRequestMethod("POST");该行: httpURLConnection.setRequestMethod("POST"); makes this an HTTP POST request and should be handled as a POST request on your server.使其成为 HTTP POST 请求,应在您的服务器上作为 POST 请求处理。

Then on your server you will need to create a new JSON object from the "PostData" which has been sent in the HTTP POST request.然后在您的服务器上,您需要从 HTTP POST 请求中发送的“PostData”创建一个新的 JSON 对象。 If you let us know what language you are using on your server then we can write up some code for you.如果您让我们知道您在服务器上使用的是什么语言,那么我们可以为您编写一些代码。

As per your current code implementation you have onPostExecute method but there is no onPreExecute and doInBackgound method.根据您当前的代码实现,您有onPostExecute方法,但没有onPreExecutedoInBackgound方法。 Starting from Android 3.0 all network operations need to be done on the background thread.从 Android 3.0 开始,所有网络操作都需要在后台线程上完成。 So you need to use Asynctask that will perform the actual sending of the request in the background and in the onPostExecute handle the result returned by the doInbackground method.因此,您需要使用Asynctask将在后台执行请求的实际发送,并在onPostExecute处理doInbackground方法返回的结果。

Here is what you need to do.这是您需要做的。

  1. Create a Asynctask class and override all the necessary methods.创建一个 Asynctask 类并覆盖所有必要的方法。
  2. The sendDeviceDetails method will eventually go inside the doInBackgound method. sendDeviceDetails方法最终将进入doInBackgound方法。
  3. onPostExecute will handle the result returned. onPostExecute将处理返回的结果。

As far as sending a JSON object is concerned, you can do it as follows,就发送JSON对象而言,您可以按如下方式进行,

Code snippet borrowed from here这里借用的代码片段

 protected void sendJson(final String email, final String pwd) {
    Thread t = new Thread() {

        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            JSONObject json = new JSONObject();

            try {
                HttpPost post = new HttpPost(URL);
                json.put("email", email);
                json.put("password", pwd);
                StringEntity se = new StringEntity( json.toString());  
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /*Checking response */
                if(response!=null){
                    InputStream in = response.getEntity().getContent(); //Get the data in the entity
                }

            } catch(Exception e) {
                e.printStackTrace();
                createDialog("Error", "Cannot Estabilish Connection");
            }

            Looper.loop(); //Loop in the message queue
        }
    };

    t.start();      
}

This is just one of the ways.这只是其中一种方式。 You can go for an Asynctask implementation as well.您也可以使用Asynctask实现。

You should use web service to send data from your app to your server because it will make your work easy and smooth.您应该使用 Web 服务将数据从您的应用程序发送到您的服务器,因为这将使您的工作轻松顺畅。 For that you have to create web service in any server side language like php,.net or even you can use jsp(java server page).为此,您必须使用任何服务器端语言(如 php、.net)创建 Web 服务,甚至可以使用 jsp(java 服务器页面)。

You have to pass all items from your Edittexts to web service.Work of adding data to server will be handled by web service您必须将 Edittexts 中的所有项目传递到 Web 服务。向服务器添加数据的工作将由 Web 服务处理

Button submitButton = (Button) findViewById(R.id.submit_button);

submitButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

        JSONObject postData = new JSONObject();

        try {
            postData.put("name", name.getText().toString());
            postData.put("address", address.getText().toString());
            postData.put("manufacturer", manufacturer.getText().toString());
            postData.put("location", location.getText().toString());
            postData.put("type", type.getText().toString());
            postData.put("deviceID", deviceID.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

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

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