Androidclient与服务端交互之登陆演示样例
今天了解了一下androidclient與服務端是如何交互的,發(fā)現事實上跟web有點類似吧,然后網上找了大神的登陸演示樣例。是基于IntentService的
1.后臺使用簡單的servlet,支持GET或POST。
這個servlet終于返回給前臺一個字符串flag,值是true或false,表示登錄是否成功。
? servlet使用之前須要配置。主義servlet的servlet-name要和servlet-mapping的servlet-name一致。否則找不到路徑
?我是在myEclipse上創(chuàng)建的一個web service 項目。然后部署到tomcatserver上以便androidclient訪問
<servlet><servlet-name>helloWorld</servlet-name><servlet-class>com.zhongzhong.wap.action.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>helloWorld</servlet-name><url-pattern>/queryOrder</url-pattern></servlet-mapping>
import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import com.zhongzhong.wap.bean.UserBean;public class HelloServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Boolean flag = false; String userName = req.getParameter("un"); String password = req.getParameter("pw"); if(userName.equals("htp")&&password.equals("123")){flag = true;}else flag = false;System.out.println("userName:"+userName+" password:"+password);out.print(flag); out.flush(); out.close(); }}
2.然后我是在安卓的ADT上創(chuàng)建一個安卓項目。建立兩個Activity,分別作為登錄界面和登錄成功界面。
<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" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="40dp"android:text="HelloWorld登陸演示樣例" /><EditTextandroid:id="@+id/et_user"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView1"android:layout_centerHorizontal="true"android:layout_marginTop="33dp"android:ems="10"android:hint="請輸入賬號" ><requestFocus /></EditText><EditTextandroid:id="@+id/et_psw"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/et_user"android:layout_centerHorizontal="true"android:layout_marginTop="40dp"android:ems="10"android:hint="請輸入password"android:inputType="textPassword" /><Buttonandroid:id="@+id/btn_login"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/et_psw"android:layout_centerHorizontal="true"android:layout_marginTop="37dp"android:text="登陸" /></RelativeLayout>
<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=".NaviActivity" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="46dp"android:text="登陸成功" /></RelativeLayout>
3.HTTP的訪問公共類,用于處理GET和POST請求
package com.example.logindemo;import java.util.ArrayList; import java.util.List; import java.util.Map;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.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;import android.content.Entity; import android.util.Log;public class HttpUtil {// 創(chuàng)建HttpClient對象public static HttpClient httpClient = new DefaultHttpClient();public static final String BASE_URL = "http://192.168.3.14:8090/HelloWord/";/*** * @param url* 發(fā)送請求的URL* @return server響應字符串* @throws Exception*/public static String getRequest(String url) throws Exception {// 創(chuàng)建HttpGet對象。HttpGet get = new HttpGet(url);// 發(fā)送GET請求HttpResponse httpResponse = httpClient.execute(get);// 假設server成功地返回響應if (httpResponse.getStatusLine().getStatusCode() == 200) {// 獲取server響應字符串String result = EntityUtils.toString(httpResponse.getEntity());return result;} else {Log.d("server響應代碼", (new Integer(httpResponse.getStatusLine().getStatusCode())).toString());return null;}}/*** * @param url* 發(fā)送請求的URL* @param params* 請求參數* @return server響應字符串* @throws Exception*/public static String postRequest(String url, Map<String, String> rawParams)throws Exception {// 創(chuàng)建HttpPost對象。
HttpPost post = new HttpPost(url); // 假設傳遞參數個數比較多的話能夠對傳遞的參數進行封裝 List<NameValuePair> params = new ArrayList<NameValuePair>(); for (String key : rawParams.keySet()) { // 封裝請求參數 params.add(new BasicNameValuePair(key, rawParams.get(key))); } // 設置請求參數 post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 發(fā)送POST請求 HttpResponse httpResponse = httpClient.execute(post); // 假設server成功地返回響應 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 獲取server響應字符串 String result = EntityUtils.toString(httpResponse.getEntity()); return result; } return null; } }
4.IntentService服務,用于在后臺以隊列方式處理耗時操作。
package com.example.logindemo;import java.util.HashMap;import android.app.IntentService; import android.content.Intent; import android.util.Log;public class ConnectService extends IntentService {private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE";public ConnectService() {super("TestIntentService");// TODO Auto-generated constructor stub}@Overrideprotected void onHandleIntent(Intent intent) {// TODO Auto-generated method stub/** * 經測試。IntentService里面是能夠進行耗時的操作的 * IntentService使用隊列的方式將請求的Intent增加隊列, * 然后開啟一個worker thread(線程)來處理隊列中的Intent * 對于異步的startService請求,IntentService會處理完畢一個之后再處理第二個 */ Boolean flag = false; //通過intent獲取主線程傳來的username與password字符串 String username = intent.getStringExtra("username"); String password = intent.getStringExtra("password"); flag = doLogin(username, password); Log.d("登錄結果", flag.toString()); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_RECV_MSG); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("result", flag.toString()); sendBroadcast(broadcastIntent); }// 定義發(fā)送請求的方法 private Boolean doLogin(String username, String password) { String strFlag = ""; // 使用Map封裝請求參數 HashMap<String, String> map = new HashMap<String, String>(); map.put("un", username); map.put("pw", password); // 定義發(fā)送請求的URL String url = HttpUtil.BASE_URL + "queryOrder?un=" + username + "&pw=" + password; //GET方式 // String url = HttpUtil.BASE_URL + "LoginServlet"; //POST方式 Log.d("url", url); Log.d("username", username); Log.d("password", password); try { // 發(fā)送請求 strFlag = HttpUtil.postRequest(url, map); //POST方式 // strFlag = HttpUtil.getRequest(url); //GET方式 Log.d("server返回值", strFlag); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(strFlag.trim().equals("true")){ return true; }else{ return false; } } }
5。
在AndroidManifest.xml中注冊IntentService。
注意uses-permission節(jié)點。為程序開啟訪問網絡的權限。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.logindemo"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="18" /><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.logindemo.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><activityandroid:name="com.example.logindemo.NaviActivity"android:label="@string/title_activity_navi" ></activity><service android:name="com.example.logindemo.ConnectService" ></service></application></manifest>
6.登陸界面處理,注意
的異常。
package com.example.logindemo;import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;public class MainActivity extends Activity {private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE";private Button loginBtn;private EditText et_username;private EditText et_password;private String userName;private String passWord;private MessageReceiver receiver ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();//動態(tài)注冊receiver IntentFilter filter = new IntentFilter(ACTION_RECV_MSG); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new MessageReceiver(); registerReceiver(receiver, filter); }private void initView() {// TODO Auto-generated method stubet_username = (EditText)findViewById(R.id.et_user);et_password =( EditText)findViewById(R.id.et_psw);loginBtn = (Button)findViewById(R.id.btn_login);loginBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(matchLoginMsg()){// 假設校驗成功 Intent msgIntent = new Intent(MainActivity.this, ConnectService.class); msgIntent.putExtra("username", et_username.getText().toString().trim()); msgIntent.putExtra("password", et_password.getText().toString().trim()); startService(msgIntent); }}});}protected boolean matchLoginMsg() {// TODO Auto-generated method stubuserName = et_username.getText().toString().trim();passWord = et_password.getText().toString().trim();if(userName.equals("")){Toast.makeText(MainActivity.this, "賬號不能為空",Toast.LENGTH_SHORT).show();return false;}if(passWord.equals("")){Toast.makeText(MainActivity.this, "密碼不能為空",Toast.LENGTH_SHORT).show();return false;}return true;}//接收廣播類 public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("result"); Log.i("MessageReceiver", message); // 假設登錄成功 if (message.equals("true")){ // 啟動Main Activity Intent nextIntent = new Intent(MainActivity.this, NaviActivity.class); startActivity(nextIntent); // 結束該Activity finish(); //注銷廣播接收器 context.unregisterReceiver(this); }else{ Toast.makeText(MainActivity.this, "用戶名或密碼錯誤,請又一次輸入!",Toast.LENGTH_SHORT).show(); } } } @Overridepublic 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;}}
執(zhí)行截圖:
轉載自http://blog.csdn.net/softwave
轉載于:https://www.cnblogs.com/hrhguanli/p/5078428.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Androidclient与服务端交互之登陆演示样例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mstsc局域网远程 要预先做的设置
- 下一篇: 安装MongoDB(做成Windows服