您需要使用一个
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对象。如果您让我们知道您的服务器上使用哪种语言,那么我们可以为您编写一些代码。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)