我有一个应用程序,我需要从我的数据库中获取一些数据(MySQL并且它保留在Web上,而不是本地)。我认为一个简单的RestFul Web服务将是我访问该数据库并获取数据的最佳选择。但是,我无法创建Web服务。我做了一些研究,但我感到困惑。我只需要访问数据库并从表中获取一些数据。请给我一些帮助来创建必要的webservice。我不希望它是一个复杂的Web服务。谢谢大家
答案 0 :(得分:1)
这是网页服务的php页面。在此userid中取自请求该数据的android java文件。然后从mySql中选择数据,它将简单地回显所有数据,并将作为响应提供给java文件。
seluser_profile.php
<?php
//$con=mysql_connect("localhost","root","");
//mysql_select_db("android_db",$con);
$con=mysql_connect("localhost","root","");
mysql_select_db("android_db",$con);
$uname=$_POST['userid'];
$q="select * from user_details where username='$uname'";
$rec=mysql_query($q);
if(mysql_num_rows($rec)==1)
{
$arr=mysql_fetch_array($rec);
echo $arr[0]+" "+$arr[2]+" "+$arr[3];
}
else
{
echo "false";
}
?>
请求Web服务的Java代码。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php");
try {
// Add your data
//Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2);
namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname'];
httppost.setEntity(new UrlEncodedFormEntity(namevpair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent()).toString();
//Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
在Asynctask类的doInBackground方法中使用此java代码。否则它会给你网络处理程序异常。
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
并且还为输入流中的字符串构建添加此函数。
答案 1 :(得分:0)
这是一个链接,你可能在冲浪时看到这个,我知道这不是答案,但我无法评论bcz我没有足够的Rep。
我在我的一个项目中使用过这个,定制非常简单..并且是一个很棒的教程。