Android客戶端與服務(wù)端交互
本文和大家一起了解了一下android客戶端與服務(wù)端是怎樣交互的,具體內(nèi)容如下
1.后臺(tái)使用簡(jiǎn)單的servlet,支持GET或POST。這個(gè)servlet最終返回給前臺(tái)一個(gè)字符串flag,值是true或false,表示登錄是否成功。
servlet使用之前需要配置,主義servlet的servlet-name要和servlet-mapping的servlet-name一致,否則找不到路徑
我是在myEclipse上創(chuàng)建的一個(gè)web service 項(xiàng)目,然后部署到tomcat服務(wù)器上以便android客戶端訪問(wèn)
<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 { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected 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)建一個(gè)安卓項(xiàng)目,建立兩個(gè)Activity,分別作為登錄界面和登錄成功界面。
<relativelayout android:layout_height="match_parent" android:layout_width="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" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <textview android:id="@+id/textView1" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_margintop="40dp" android:layout_width="wrap_content" android:text="HelloWorld登陸示例"> <edittext android:ems="10" android:hint="請(qǐng)輸入賬號(hào)" android:id="@+id/et_user" android:layout_below="@+id/textView1" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_margintop="33dp" android:layout_width="wrap_content"> <requestfocus> </requestfocus></edittext> <edittext android:ems="10" android:hint="請(qǐng)輸入密碼" android:id="@+id/et_psw" android:inputtype="textPassword" android:layout_below="@+id/et_user" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_margintop="40dp" android:layout_width="wrap_content"><button android:id="@+id/btn_login" android:layout_below="@+id/et_psw" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_margintop="37dp" android:layout_width="wrap_content" android:text="登陸"></button></edittext></textview></relativelayout> <relativelayout android:layout_height="match_parent" android:layout_width="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" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <textview android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_margintop="46dp" android:layout_width="wrap_content" android:text="登陸成功"> </textview></relativelayout>
3.HTTP的訪問(wèn)公共類,用于處理GET和POST請(qǐng)求。
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對(duì)象 public static HttpClient httpClient = new DefaultHttpClient(); public static final String BASE_URL = http://192.168.3.14:8090/HelloWord/; /** * * @param url * 發(fā)送請(qǐng)求的URL * @return 服務(wù)器響應(yīng)字符串 * @throws Exception */ public static String getRequest(String url) throws Exception { // 創(chuàng)建HttpGet對(duì)象。 HttpGet get = new HttpGet(url); // 發(fā)送GET請(qǐng)求 HttpResponse httpResponse = httpClient.execute(get); // 如果服務(wù)器成功地返回響應(yīng) if (httpResponse.getStatusLine().getStatusCode() == 200) { // 獲取服務(wù)器響應(yīng)字符串 String result = EntityUtils.toString(httpResponse.getEntity()); return result; } else { Log.d(服務(wù)器響應(yīng)代碼, (new Integer(httpResponse.getStatusLine() .getStatusCode())).toString()); return null; } } /** * * @param url * 發(fā)送請(qǐng)求的URL * @param params * 請(qǐng)求參數(shù) * @return 服務(wù)器響應(yīng)字符串 * @throws Exception */ public static String postRequest(String url, Map<string, string=""> rawParams) throws Exception { // 創(chuàng)建HttpPost對(duì)象。 HttpPost post = new HttpPost(url); // 如果傳遞參數(shù)個(gè)數(shù)比較多的話可以對(duì)傳遞的參數(shù)進(jìn)行封裝 List<namevaluepair> params = new ArrayList<namevaluepair>(); for (String key : rawParams.keySet()) { // 封裝請(qǐng)求參數(shù) params.add(new BasicNameValuePair(key, rawParams.get(key))); } // 設(shè)置請(qǐng)求參數(shù) post.setEntity(new UrlEncodedFormEntity(params, UTF-8)); // 發(fā)送POST請(qǐng)求 HttpResponse httpResponse = httpClient.execute(post); // 如果服務(wù)器成功地返回響應(yīng) if (httpResponse.getStatusLine().getStatusCode() == 200) { // 獲取服務(wù)器響應(yīng)字符串 String result = EntityUtils.toString(httpResponse.getEntity()); return result; } return null; } } </namevaluepair></namevaluepair></string,>
4.IntentService服務(wù),用于在后臺(tái)以隊(duì)列方式處理耗時(shí)操作。
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 } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub /** * 經(jīng)測(cè)試,IntentService里面是可以進(jìn)行耗時(shí)的操作的 * IntentService使用隊(duì)列的方式將請(qǐng)求的Intent加入隊(duì)列, * 然后開啟一個(gè)worker thread(線程)來(lái)處理隊(duì)列中的Intent * 對(duì)于異步的startService請(qǐng)求,IntentService會(huì)處理完成一個(gè)之后再處理第二個(gè) */ Boolean flag = false; //通過(guò)intent獲取主線程傳來(lái)的用戶名和密碼字符串 String username = intent.getStringExtra(username); String password = intent.getStringExtra(password); flag = doLogin(username, password); Log.d(登錄結(jié)果, flag.toString()); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_RECV_MSG); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra(result, flag.toString()); sendBroadcast(broadcastIntent); } // 定義發(fā)送請(qǐng)求的方法 private Boolean doLogin(String username, String password) { String strFlag = ; // 使用Map封裝請(qǐng)求參數(shù) HashMap<string, string=""> map = new HashMap<string, string="">(); map.put(un, username); map.put(pw, password); // 定義發(fā)送請(qǐng)求的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ā)送請(qǐng)求 strFlag = HttpUtil.postRequest(url, map); //POST方式 // strFlag = HttpUtil.getRequest(url); //GET方式 Log.d(服務(wù)器返回值, strFlag); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(strFlag.trim().equals(true)){ return true; }else{ return false; } } } </string,></string,>
5.在AndroidManifest.xml中注冊(cè)IntentService。注意uses-permission節(jié)點(diǎn),為程序開啟訪問(wèn)網(wǎng)絡(luò)的權(quán)限。
<!--?xml version=1.0 encoding=utf-8?--> <manifest android:versioncode="1" android:versionname="1.0" package="com.example.logindemo" xmlns:android="http://schemas.android.com/apk/res/android"> <uses-sdk android:minsdkversion="8" android:targetsdkversion="18"> <uses-permission android:name="android.permission.INTERNET"> <intent-filter> <category android:name="android.intent.category.LAUNCHER"> </category></action></intent-filter> </activity> </activity> <service android:name="com.example.logindemo.ConnectService"> </service> </application> </uses-permission></uses-sdk></manifest>
6.登陸界面處理,注意
按鈕監(jiān)聽事件中,使用Intent將要傳遞的值傳給service。接收廣播類中,同樣使用Intent將要傳遞的值傳給下一個(gè)Activity。在onCreate()中,動(dòng)態(tài)注冊(cè)接收廣播類的實(shí)例receiver。在接收廣播類中,不要使用完畢后忘記注銷接收器,否則會(huì)報(bào)一個(gè)Are you missing a call to unregisterReceiver()? 的異常。
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 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); //動(dòng)態(tài)注冊(cè)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 stub et_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() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(matchLoginMsg()) { // 如果校驗(yàn)成功 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 stub userName = et_username.getText().toString().trim(); passWord = et_password.getText().toString().trim(); if(userName.equals()) { Toast.makeText(MainActivity.this, 賬號(hào)不能為空,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)){ // 啟動(dòng)Main Activity Intent nextIntent = new Intent(MainActivity.this, NaviActivity.class); startActivity(nextIntent); // 結(jié)束該Activity finish(); //注銷廣播接收器 context.unregisterReceiver(this); }else{ Toast.makeText(MainActivity.this, 用戶名或密碼錯(cuò)誤,請(qǐng)重新輸入!,Toast.LENGTH_SHORT).show(); } } } @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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Android實(shí)現(xiàn)自定義圓形進(jìn)度條
這篇文章主要介紹了Android自定義圓形進(jìn)度條實(shí)現(xiàn)代碼,進(jìn)度條在Android中教程經(jīng)常使用到,本文向大家分享了Android實(shí)現(xiàn)自定義圓形進(jìn)度條的代碼,感興趣的小伙伴們可以參考一下2016-03-03Android EditTextView 實(shí)現(xiàn)帶空格分隔的輸入(電話號(hào)碼,銀行卡)
這篇文章主要介紹了Android EditTextView 實(shí)現(xiàn)帶空格分隔的輸入(電話號(hào)碼,銀行卡)的相關(guān)資料,需要的朋友可以參考下2018-02-02Android編程實(shí)現(xiàn)開始及停止service的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)開始及停止service的方法,涉及Android針對(duì)service的開始、停止、綁定等操作相關(guān)技巧與注意事項(xiàng),需要的朋友可以參考下2016-01-01Android實(shí)現(xiàn)底部圖片選擇Dialog
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)底部圖片選擇Dialog,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10詳解關(guān)于AndroidQ獲取不到imsi解決方案
這篇文章主要介紹了詳解關(guān)于AndroidQ獲取不到imsi解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Android中EditText光標(biāo)在4.0中的bug及解決方法
這篇文章主要介紹了Android中EditText光標(biāo)在4.0中的bug及解決方法,簡(jiǎn)單分析了Android4.0版本中EditText光標(biāo)消息的原因及相應(yīng)的解決方法,需要的朋友可以參考下2016-01-01Android實(shí)現(xiàn)大圖滾動(dòng)顯示效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)大圖滾動(dòng)顯示效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12Android仿Keep運(yùn)動(dòng)休息倒計(jì)時(shí)圓形控件
這篇文章主要為大家詳細(xì)介紹了Android仿Keep運(yùn)動(dòng)休息倒計(jì)時(shí)圓形控件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09Android利用Palette實(shí)現(xiàn)提取圖片顏色
Palette是一個(gè)類似調(diào)色板的工具類,根據(jù)傳入的bitmap,提取出主體顏色,使得圖片和顏色更加搭配,界面更協(xié)調(diào)。本文將詳解如何利用Palette實(shí)現(xiàn)提取圖片顏色,需要的可以參考一下2022-03-03Android實(shí)現(xiàn)拍照、選擇圖片并裁剪圖片功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)拍照、選擇圖片并裁剪圖片功能的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05