当前位置: 首页 > 知识库问答 >
问题:

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

利永年
2023-03-14

对于如何将一个< code>json对象从我的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;


    }


}


   

共有3个答案

储俊英
2023-03-14

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

这是你需要做的。

    < li >创建一个Asynctask类并覆盖所有必要的方法。 < Li > < code > sendevicedetails 方法最终将进入< code>doInBackgound方法内部。 < li> onPostExecute将处理返回的结果。

就发送<code>JSON</code>对象而言,您可以按如下方式执行:,

从这里借用的代码片段

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

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

燕扬
2023-03-14

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

您必须将所有项目从您的编辑文本传递到Webservice.Work将数据添加到服务器将由Web服务处理

谷永贞
2023-03-14

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

这是在您的< code>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
    }
}

行:<code>httpURLConnection。setRequestMethod(“POST”)将此设置为HTTP POST请求,并应在服务器上作为POST请求处理。

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

 类似资料:
  • 问题内容: 关于如何将对象从我的android应用程序发送到数据库,我 有点茫然 由于我是新手,所以我不太确定哪里出了问题,我从中提取了数据,我不知道如何将对象发布到我们的服务器。 任何建议将不胜感激 问题答案: 您需要使用一个类与服务器进行通信。像这样: 这是您的方法。 这是您的活动课程中的新课程。 这行:将其作为HTTP POST请求,应在您的服务器上作为POST请求处理。 然后,在服务器上,

  • 我尝试从http://developer.android.com/guide/google/gcm/gs.html我可以将regid发送到servlet,但无法从中获取消息。 Servlet: GCMinentService: 控制台: 我怎样才能解决这个问题?

  • 在我的应用程序中,我希望在崩溃时将日志发送到远程服务器。我添加了try-catch块,并在catch中向服务器发送日志。我想知道我应该抓住哪些例外。我需要日志以防每次崩溃,这样我就能修复它。捕捉所有异常是一种好的做法吗? 提前感谢。

  • 问题内容: 我正在开发我的第一个Android应用程序。我正在尝试做的是对REST服务的POST请求,我希望此请求的主体为JSON字符串。 我正在使用Google的GSON来生成发送到服务器的JSON。这是执行POST请求的代码: 响应代码为400 BAD REQUEST,我可以从服务器日志中读取信息。尸体未正确发送的地方: 服务器端的代码是一个简单的Seam Rest Service: Andr

  • 我正在尝试从Android向我的php服务器提交数据。然而,所有的答案似乎都使用了不推荐使用的ApacheHTTP库。我不想用它,当我试着用的时候,它不起作用。 现在它似乎什么也没做。它似乎连接到web服务器,但服务器不写入任何数据。如果我只是用浏览器访问url,它会写入一个文件。 php代码是 然后在Android studio中,我会在按下按钮后放入所有代码

  • 我正在用Android开发一个应用程序。我不知道如何从应用程序发送电子邮件?