栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从我的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对象。如果您让我们知道您的服务器上使用哪种语言,那么我们可以为您编写一些代码。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636702.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号