我在这里要做的是在我们的示例网页上发送一个字符串数据。我很确定我的代码没有遗漏任何内容,并且在运行应用程序时没有错误,但我仍然无法将数据发送到我们的网页。http://icommute-ph.com/
我有两个类,一个是测试我是否可以使用 JSON 发送用户输入数据字符串,代码如下:
private class reqData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://icommute-ph.com/api/v1/todos/");
try
{
// Add your data
JSONObject user = new JSONObject();
try
{
user.put("Name", tstData.getText().toString());
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create StringEntity
StringEntity se = new StringEntity(user.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException cpe) {
// TODO Auto-generated catch block
cpe.printStackTrace();
} catch (IOException ioe) {
// TODO Auto-generated catch block
ioe.printStackTrace();
}
return null;
}
}//end of class reqData
这是我用来使用 REST 发送数据的另一个类 注意:我真的很确定这个类会起作用,因为我试图在我们的另一个网页中这样做。
public class reqDataREST extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://icommute-ph.com/api/v1/todos/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Name", tstData.getText().toString()));
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
BasicHttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
// Execute HTTP Post Request
HttpResponse response = client.execute(postRequest, httpContext);
//int statusCode = response.getStatusLine().getStatusCode();
}
catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
}
catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
}
return null;
}
}// end of reqRoute class
当我单击一个按钮时,用户输入数据应发送到我们的示例网页。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tstData = (AutoCompleteTextView) findViewById(R.id.testData);
sndRequest = (Button) findViewById(R.id.btnSend);
sndRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new reqData().execute();
new reqDataREST().execute();
//ALERT MESSAGE
Toast.makeText(getBaseContext(),"Sending Request, Please Wait...",Toast.LENGTH_LONG).show();
}
});//end of onClickListener
}
}
可以请任何人在这里帮助我,我只是 json 的新手...这是我们示例网页中的一些详细信息:http: //icommute-ph.com/api/v1/todos/ ?format=json