【问题标题】:How To Send json Object to the server from my android app如何从我的 android 应用程序将 json 对象发送到服务器
【发布时间】:2016-05-25 06:35:41
【问题描述】:

对于如何将jsonobject 从我的 android 应用程序发送到数据库,我有点不知所措

由于我是新手,我不太确定哪里出错了,我从XML 中提取了数据,但我不知道如何将对象发布到我们的服务器。

任何建议都将不胜感激

 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;


    }


}


   

【问题讨论】:

  • 您可以通过将 JSONObject 转换为字符串来将其发送到服务器。我不确定您面临什么问题。能详细点就更好了
  • 我被告知我们只能将其作为对象发送,我知道如何将其作为字符串发送,但不知道如何将其作为对象发送

标签: android json


【解决方案1】:

您需要使用AsyncTask 类与您的服务器进行通信。像这样的:

这是在您的 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();
        }
    }
});

这是您的活动课程中的一个新课程。

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

这行:httpURLConnection.setRequestMethod("POST"); 使它成为一个 HTTP POST 请求,应该在您的服务器上作为一个 POST 请求来处理。

然后在您的服务器上,您需要从 HTTP POST 请求中发送的“PostData”创建一个新的 JSON 对象。如果您让我们知道您在服务器上使用的语言,那么我们可以为您编写一些代码。

【讨论】:

  • 所以我做了所有这些更改,但它似乎没有发送任何内容,并且 logcat 中没有显示任何内容表明它正在发送。我们将不胜感激
  • @TomFisher 你应该在我给你的代码中添加一些Log.e("TAG", variable);。在String data = ""; 行上方,添加Log.e("TAG", params[0]);Log.e("TAG", params[1]); 以检查SendDeviceDetails 类是否正确执行,还要在return data; 行上方添加Log.e("TAG", data);。如果 logcat 中没有任何内容,那么它会让我认为它没有被执行。还要确保您已在清单中添加互联网权限。
  • 是的,我这样做了,但是 logcat 中没有显示任何内容,所以我把它们放在了所有地方,似乎按钮没有响应被点击。
  • 啊,我刚刚注意到public void onClick(View v) { 上方没有@Override,请尝试将其重新添加或重写整个setOnClickListener 部分代码使用来自您的IDE 的建议(假设您IDE 为您提供与 Android Studio 类似的建议。
  • 当我添加@overide 时出现错误,尝试重做它仍然没有。没有错误,它根本无法识别点击
【解决方案2】:

您应该使用网络服务将数据从您的应用程序发送到您的服务器,因为这将使您的工作变得轻松顺畅。为此,您必须使用任何服务器端语言(如 php、.net)创建 Web 服务,甚至可以使用 jsp(java 服务器页面)。

您必须将 Edittexts 中的所有项目传递给 Web 服务。将数据添加到服务器的工作将由 Web 服务处理

【讨论】:

  • 我们已经有一个网络服务,但它没有提供给我们,只有 URL
【解决方案3】:

根据您当前的代码实现,您有onPostExecute 方法,但没有onPreExecutedoInBackgound 方法。从 Android 3.0 开始,所有网络操作都需要在后台线程上完成。所以你需要使用Asynctask,它将在后台执行请求的实际发送,并在onPostExecute处理doInbackground方法返回的结果。

这是你需要做的。

  1. 创建一个 Asynctask 类并覆盖所有必要的方法。
  2. sendDeviceDetails 方法最终将进入doInBackgound 方法。
  3. onPostExecute 将处理返回的结果。

就发送JSON对象而言,可以如下进行,

here借来的代码sn-p

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

这只是其中一种方式。您也可以使用Asynctask 实现。

【讨论】:

    【解决方案4】:
    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();
            }
        }
    });
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2013-09-09
    相关资源
    最近更新 更多