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

如何从我的Android应用程序将json对象发送到服务器,第1张

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

您需要使用一个

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 pre to be sent from your server upon receiving the POST data    }}

这行:

httpURLConnection.setRequestMethod("POST");
将其作为HTTP
POST请求,应在您的服务器上作为POST请求处理。

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642535.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存