📜  Android Web服务教程

📅  最后修改于: 2020-10-11 03:59:03             🧑  作者: Mango

Android Web服务教程

在android中创建Web服务应用程序并非难事。我们可以使用android,.net,php等语言开发的其他应用程序轻松地在android中创建一个宁静的Web服务应用程序,以将信息认证或保存到外部数据库中,例如oracle,mysql,postgre sql,sql server。那就是我们要做的。

Android Restful Web服务教程

在开发Web服务应用程序之前,您必须具有SOAP和Restful Web服务的基本知识。因此,我们将讨论有关Web服务的基本要点,例如什么是Web服务以及有关SOAP和Restful Web服务的简要信息。

什么是Web服务?

Web服务是用于在不同类型的应用程序之间交换信息的标准,而与语言和平台无关。例如,Android应用程序可以使用Web服务与Java或.net应用程序进行交互。

Android Restful Web服务示例



    

        
    

    

    

文件:activity_register_user.xml



    

    

    

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
    {

@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 list=new ArrayList();
    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;

}

}

RegisterUser类

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
    {

@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 list=new ArrayList();
    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权限。




    

    

    
        
            
                

                
            
        
        
        
    


输出:


使用oracle数据库的Java Servlet登录和注册示例

在Oracle数据库中创建具有三列ID,名称和密码的表javatpoint_user。 ID必须是主键,并通过SEQUENCE生成。

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

新创建两个servlet类来登录和注册用户。

登录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

Name:
Password: