大家好,我开始研究android中的webservices,我试图将我的android应用程序中的信息保存到服务器
首先我做了一个php文件。我尝试使用它插入代码。我使用这个PHP代码文件
成功插入代码<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO user_records (user_name, email)
VALUES ('$uname', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
在此之后,我尝试通过点击url将信息从我的应用程序发送到服务器。我使用的代码是
public class MainActivity extends Activity {
TextView tv1;
HttpClient httpclient;
HttpPost httppost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/name.php");
new getresult().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class getresult extends AsyncTask<Void, Void, Void>{
String result = null;
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("uname", "rocky"));
nameValuePairs.add(new BasicNameValuePair("email", "rockss"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result1) {
// TODO Auto-generated method stub
super.onPostExecute(result1);
tv1.setText("Data Inserted");
//Log.i("My Response :: ", result);
}
}
}
在textview中我得到了这条消息,即Data Inserted,但问题是该值未插入数据库中。
所以,如果你们有人告诉我我犯了什么错误。这对我很有帮助。提前致谢
答案 0 :(得分:1)
您需要执行HTTP POST请求:
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("uname", "rocky"));
nameValuePairs.add(new BasicNameValuePair("email", "rockss"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
String resp = httpClient.execute(httpPost, new BasicResponseHandler());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.toString());
}
要从代码中获取服务器使用的数据:
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
// put the parameters if needed
String resp = httpClient.execute(httpPost, new BasicResponseHandler());
String[] nameEmailPairs = resp.split("<br>");
for(String pair : nameEmailPairs){
String[] par = pair.split(" ");
String name = par[0];
String email = par[1];
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.toString());
}
答案 1 :(得分:0)
您可以为http请求使用简单的框架。 http://loopj.com/android-async-http/使用非常简单,并在发送请求后提供回调,成功和失败。这都是自动化的。
这是一个例子
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
答案 2 :(得分:0)
Web服务初学者的小项目。我是网络服务的初学者,所以我做了一些事情,我想为初学者分享,以便他们知道如何使用webservices
首先我制作了2个php文件
第一个用这个我可以在abhi_db数据库,user_records表上保存数据,用2列user_name和email
因为我没有服务器。因为我使用localhost所以我使用localhost,用户名是root,密码我没有设置所以我把它留空
<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO user_records (user_name, email)
VALUES ('$uname', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
使用这个PHP代码,我可以通过从我的应用程序中获取值来保存数据库中的值 注意:不要忘记在phpmyadmin中使用您使用的表名创建数据库
第二个php文件是
<?php
$con=mysqli_connect("localhost","root","","abhi_DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM user_records");
while($row = mysqli_fetch_array($result)) {
echo $row['user_name'] . " " . $row['email'];
echo "<br>";
}
mysqli_close($con);
?>
第二个代码是将数据保存在数据库中
现在来到android代码:
现在从android我们将点击url
在MainActivity类
中public class MainActivity extends Activity {
TextView tv1;
HttpClient httpclient;
HttpPost httppost;
EditText edname, edemail;
Button Submit, GetData;
String geted1, geted2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
edname = (EditText) findViewById(R.id.editText1);
edemail = (EditText) findViewById(R.id.editText2);
Submit = (Button) findViewById(R.id.button1);
GetData = (Button) findViewById(R.id.button2);
httppost = new HttpPost("http://10.0.2.2/name.php");
Submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
geted1 = edname.getText().toString();
geted2 = edemail.getText().toString();
Log.i("Name", geted1);
Log.i("Email", geted2);
new getresult().execute();
}
});
GetData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, GetNameDemo.class);
startActivity(i);
}
});
}
public class getresult extends AsyncTask<Void, Void, Void> {
String result = null;
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
httpclient = new DefaultHttpClient(params);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("uname", geted1));
nameValuePairs.add(new BasicNameValuePair("email", geted2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"utf-8"));
result = httpclient.execute(httppost,
new BasicResponseHandler());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result1) {
// TODO Auto-generated method stub
super.onPostExecute(result1);
tv1.setText("" + result);
// Log.i("My Response :: ", result);
}
}
}
在MainActivity类中,我使用了两个edittext一个用于名称,第二个用于电子邮件,单击提交按钮我将值发送到服务器并在Getdata按钮上单击我启动了Activity类GetNameDemo,其中我获取了所有保存的行
public class GetNameDemo extends Activity {
TextView tv1,tv2;
HttpClient httpclient;
HttpPost httppost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
httppost = new HttpPost("http://10.0.2.2/getname.php");
new getresult().execute();
}
public class getresult extends AsyncTask<Void, Void, Void>{
String name = "Names";
String email = " Emails";
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
httpclient = new DefaultHttpClient(params);
String resp = httpclient.execute(httppost, new BasicResponseHandler());
String[] nameEmailPairs = resp.split("<br>");
for(String pair : nameEmailPairs){
String[] par = pair.split(" ");
name = name + " \n " +par[0];
email = email + "\n " + par[1];
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result1) {
// TODO Auto-generated method stub
super.onPostExecute(result1);
tv1.setText("" +name );
tv2.setText( "" +email);
//Log.i("My Response :: ", result);
}
}
}
注意添加权限<uses-permission android:name="android.permission.INTERNET"/>
和活动<activity android:name="GetNameDemo"></activity>