Android Web Service 教程含代碼

Android Web Service 教程

在安卓中創建Web服務應用并不是一項困難的任務。愛掏網 - it200.com我們可以輕松地創建一個Restful Web服務應用,用于在安卓中驗證或將信息保存到外部數據庫,比如Oracle、MySQL、PostgreSQL、SQL Server,這些數據庫是使用Java、.Net、PHP等語言開發的應用程序。愛掏網 - it200.com這就是我們要做的。愛掏網 - it200.com

在開發Web服務應用之前,你必須對SOAP和Restful Web服務有基本的了解。愛掏網 - it200.com因此,我們將討論關于Web服務的基本知識,例如什么是Web服務以及關于SOAP和Restful Web服務的簡要信息。愛掏網 - it200.com

什么是Web服務?

Web服務是在不考慮語言和平臺的情況下,不同類型應用程序之間交換信息的標準。愛掏網 - it200.com例如,安卓應用程序可以通過Web服務與Java或.Net應用程序進行交互。愛掏網 - it200.com

安卓Restful Web服務示例

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Username"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="67dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="24dp"
        android:layout_toRightOf="@+id/button1"
        android:text="New User" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="22dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/progressBar1"
        android:layout_marginLeft="22dp"
        android:text="Login" />

</RelativeLayout>

文件:activity_register_user.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Enter UserName" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="50dp"
        android:ems="10"
        android:hint="Enter Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Resister" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="87dp" />

</RelativeLayout>

MainActivity類

package com.example.newrestapi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText password,userName;
    Button login,resister;
    ProgressBar progressBar;



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        password=(EditText) findViewById(R.id.editText2);
        userName=(EditText) findViewById(R.id.editText1);
        login=(Button) findViewById(R.id.button1);
        resister=(Button) findViewById(R.id.button2);

        //progess_msz.setVisibility(View.GONE);
        progressBar=(ProgressBar) findViewById(R.id.progressBar1);
        progressBar.setVisibility(View.GONE);


        resister.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent  intent=new Intent(MainActivity.this,ResisterUser.class);
                startActivity(intent);
            }
        });
        login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);

                String s1=userName.getText().toString();
                String s2=password.getText().toString();
                new ExecuteTask().execute(s1,s2);

            }
        });


    }

     class ExecuteTask extends AsyncTask<String, Integer, String>
        {

            @Override
            protected String doInBackground(String... params) {

                String res=PostData(params);

                return res;
            }

            @Override
            protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
            //progess_msz.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), result, 3000).show();
            }

        }

    public String PostData(String[] valuse) {
        String s="";
        try
        {
        HttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/Login");

        List<NameValuePair> list=new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("name", valuse[0]));
        list.add(new BasicNameValuePair("pass",valuse[1]));
        httpPost.setEntity(new UrlEncodedFormEntity(list));
        HttpResponse httpResponse=  httpClient.execute(httpPost);

        HttpEntity httpEntity=httpResponse.getEntity();
        s= readResponse(httpResponse);

        }
        catch(Exception exception)  {}
        return s;


    }
    public String readResponse(HttpResponse res) {
        InputStream is=null; 
        String return_text="";
        try {
            is=res.getEntity().getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
            String line="";
            StringBuffer sb=new StringBuffer();
            while ((line=bufferedReader.readLine())!=null)
            {
            sb.append(line);
            }
            return_text=sb.toString();
        } catch (Exception e)
        {

        }
        return return_text;

    }

}

注冊用戶類

package com.example.newrestapi;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class ResisterUser extends Activity {
     EditText userName,passwprd;
       Button resister,login;
       ProgressBar progressBar;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_resister_user);
            userName=(EditText) findViewById(R.id.editText1);;
            passwprd=(EditText) findViewById(R.id.editText2);
            resister=(Button) findViewById(R.id.button1);

            progressBar=(ProgressBar) findViewById(R.id.progressBar1);
            progressBar.setVisibility(View.GONE);

            resister.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    progressBar.setVisibility(View.VISIBLE);

                    String s1=userName.getText().toString();
                    String s2=passwprd.getText().toString();
                    new ExecuteTask().execute(s1,s2);
                }
            });




        }

        class ExecuteTask extends AsyncTask<String, Integer, String>
        {

            @Override
            protected String doInBackground(String... params) {

                PostData(params);
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
            }

        }



        public void PostData(String[] valuse) {
            try
            {
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost(
                                  "http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet");
            List<NameValuePair> list=new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("name", valuse[0]));
            list.add(new BasicNameValuePair("pass",valuse[1]));
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            httpClient.execute(httpPost);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }

        }

        }

您需要在AndroidManifest.xml文件中提供INTERNET權限。愛掏網 - it200.com

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.newrestapi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.newrestapi.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.newrestapi.ResisterUser"
            android:label="@string/title_activity_resister_user" >
        </activity>
    </application>

</manifest>

輸出:

Java Servlet登錄和注冊示例,使用oracle數據庫

在oracle數據庫中創建表javatpoint_user,包含三個列id、name和password。愛掏網 - it200.comid必須是主鍵,并通過SEQUENCE生成。愛掏網 - it200.com

CREATE TABLE  "JAVATPOINT_USER" 
   (    "ID" NUMBER, 
    "NAME" VARCHAR2(4000), 
    "PASSWORD" VARCHAR2(4000), 
     CONSTRAINT "JAVATPOINT_USER_PK" PRIMARY KEY ("ID") ENABLE
   )
/

新建兩個servlet類來登錄和注冊用戶。愛掏網 - it200.com

登錄Servlet類

package server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html");  

            ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());

            String n=request.getParameter("name");  
            String p=request.getParameter("pass");
            System.out.println(n);
            System.out.println(p);

            if(validate(n, p)){  
               out.writeObject("success");

            }  
            else{  
               out.writeObject("Sorry username or password error");

            }  

            out.close();  
            }  


    public static boolean validate(String name,String pass){  
        boolean status=false;  
        try{  
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection(
                      "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

        PreparedStatement ps=con.prepareStatement(  
        "select * from javatpoint_user where name=? and password=?");  
        ps.setString(1,name);  
        ps.setString(2,pass);  

        ResultSet rs=ps.executeQuery();  
        status=rs.next();  

        }catch(Exception e){System.out.println(e);}  
        return status;  
        }  
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException, IOException {
doGet(request, response);

}
}

httpPostServlet Servlet類

package server;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class httpPostServlet extends HttpServlet {


     public void doGet(HttpServletRequest request,HttpServletResponse response)
     throws ServletException, IOException {
 response.setContentType("text/html");
String recived_data="";


 String s1=request.getParameter("name");
 String s2=request.getParameter("pass");
 System.out.println(s1);
 System.out.println(s2);    

        try
        {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection(
                       "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
        PreparedStatement ps=con.prepareStatement(
                      "insert into javatpoint_user(name,password) values(?,?)");
        ps.setString(1, s1);
        ps.setString(2,s2);
        ps.executeUpdate();
        con.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

} 
public void doPost(HttpServletRequest request,HttpServletResponse response)
     throws ServletException, IOException {
 doGet(request, response);
}

}

index.jsp

<form action="servlet/Login">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="pass"/><br/>
<input type="submit" value="login"/>
</form>

聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
發表評論
更多 網友評論0 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 在线视频免费观看www动漫| 美女脱下裤子让男人捅| 无码人妻精品一区二区三18禁| 别揉我胸啊嗯上课呢的作文| 中文字幕第5页| 男女一级免费视频| 国产欧美日韩精品综合| 中文字幕亚洲激情| 老师的胸好大好软| 新梅瓶1一5集在线观看| 亚洲色欲久久久综合网| 久久精品老司机| 尹人香蕉久久99天天| 亚洲伊人久久精品影院| 美国式禁忌5太大了| 国产精品亚洲综合| 三年片在线观看免费观看大全中国| 欧美日本另类xxx乱大交| 国产v片成人影院在线观看| 8av国产精品爽爽ⅴa在线观看| 日本免费小视频| 亚洲欧美日本另类| 翁虹一级毛片手机观看| 国产精品免费精品自在线观看| 中文字幕av无码不卡免费 | 大乳女人做受视频免费观看| 久久综合久久鬼色| 波多野结衣教室| 国产午夜电影在线观看| 三级韩国床戏3小时合集| 欧美五级在线观看视频播放| 公与2个熄乱理在线播放| 黄a大片av永久免费| 在线综合 亚洲 欧美中文字幕| 久久精品人人爽人人爽| 污污污污污污www网站免费| 国产AV寂寞骚妇| ts人妖系列在线专区| 97国产在线视频公开免费| 999在线视频精品免费播放观看| 欧美成人在线视频|