如何从我的android应用程序向服务器发送json对象
对于如何将如何从我的android应用程序向服务器发送json对象,android,json,Android,Json,对于如何将json对象从android应用程序发送到数据库,我有点不知所措 由于我是新手,我不太确定哪里出了问题,我从XML中提取了数据,我不知道如何将对象发布到我们的服务器 任何建议都将不胜感激 package mmu.tom.linkedviewproject; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatAc
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;
}
}
根据您当前的代码实现,您有
onPostExecute
方法,但没有onPreExecute
和doInBackgound
方法。从Android 3.0开始,所有网络操作都需要在后台线程上完成。因此,您需要使用Asynctask
,它将在后台执行请求的实际发送,并在onPostExecute
中处理doInbackground
方法返回的结果
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();
}
}
});
这是你需要做的
sendDeviceDetails
方法最终将进入doInBackgound
方法中李>
onPostExecute
将处理返回的结果JSON
对象而言,您可以按如下方式执行:
借用自
这只是其中一种方法。您也可以执行
异步任务。您应该使用web服务将数据从应用程序发送到服务器,因为它将使您的工作轻松顺畅。为此,您必须使用任何服务器端语言(如php、.net)创建web服务,甚至可以使用jsp(java服务器页面)
您必须将所有项目从EditText传递到web服务。向服务器添加数据的工作将由web服务处理您需要使用异步任务
类与服务器通信。大概是这样的:
这在您的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
}
}
私有类SendDeviceDetails扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串数据=”;
HttpURLConnection HttpURLConnection=null;
试一试{
httpURLConnection=(httpURLConnection)新URL(参数[0]).openConnection();
httpURLConnection.setRequestMethod(“POST”);
httpURLConnection.setDoOutput(true);
DataOutputStream wr=新的DataOutputStream(httpURLConnection.getOutputStream());
writeBytes(“PostData=“+params[1]);
wr.flush();
wr.close();
InputStream in=httpURLConnection.getInputStream();
InputStreamReader InputStreamReader=新的InputStreamReader(in);
int inputStreamData=inputStreamReader.read();
while(inputStreamData!=-1){
char current=(char)inputStreamData;
inputStreamData=inputStreamReader.read();
数据+=当前数据;
}
}捕获(例外e){
e、 printStackTrace();
}最后{
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
Log.e(“TAG”,result);//这期望在收到POST数据时从服务器发送响应代码
}
}
行:httpURLConnection.setRequestMethod(“POST”)
使其成为HTTP POST请求,并应在服务器上作为POST请求处理
然后,在服务器上,您需要从HTTP POST请求中发送的“PostData”创建一个新的JSON对象。如果您让我们知道您在服务器上使用的语言,那么我们可以为您编写一些代码。您可以通过将JSONObject转换为字符串将其发送到服务器。我不知道你面临什么问题。如果你能详细说明就更好了我被告知我们只能将其作为对象发送,我知道如何将其作为字符串发送,但不知道如何将其作为对象发送我们已经有了一个Web服务,但它没有提供给我们,只有URLSO我已经做了所有这些更改,但它似乎没有发送任何内容,日志中没有显示它正在发送。而帮助将是apreciated@TomFisher您应该添加一些Log.e(“TAG”,variable)代码>在我给你的代码中。行上方<代码>字符串数据=”代码>,外接程序Log.e(“标记”,参数[0])代码>和Log.e(“标记”,参数[1])
要检查SendDeviceDetails类是否正确执行,还需要添加Log.e(“TAG”,data)代码>行上方<代码>返回数据代码>。如果日志中没有任何内容,那么它会让我认为它没有被执行。还要确保您在清单中添加了internet权限。是的,我这样做了,但日志中没有显示任何内容,因此我将它们放在了所有位置,似乎按钮对被单击没有响应。啊,我刚刚注意到,在public void onClick(视图五)上方没有@覆盖{
,尝试将其添加回或使用IDE中的建议重写整个setOnClickListener
部分代码(假设IDE向您提供类似Android Studio的建议)。我只是在添加@overide时出错,尝试重做,但仍然没有结果。没有错误,它根本无法识别单击。请不要只发布代码作为答案,还要提供一个解释,说明代码的作用以及它如何解决问题。带有解释的答案通常更有用,质量更好而且更有可能吸引更多的选票。
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();
}
}
});