日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android之网络编程

發布時間:2024/7/23 Android 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android之网络编程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文主要包括三方面內容

  • Httpurlconnection中doGet與doPost方法實現提交數據到服務器

  • HttpClient中doGet與doPost方法實現提交數據到服務器

  • android-async-http開源庫方法實現提交數據到服務器

  • 首先是服務器端的實現

    public class LoginServlet extends HttpServlet {/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username"); // 采用的編碼是: iso-8859-1String password = request.getParameter("password");// 采用iso8859-1的編碼對姓名進行逆轉, 轉換成字節數組, 再使用utf-8編碼對數據進行轉換, 字符串username = new String(username.getBytes("iso8859-1"), "utf-8");password = new String(password.getBytes("iso8859-1"), "utf-8");System.out.println("姓名: " + username);System.out.println("密碼: " + password);if("lisi".equals(username) && "123".equals(password)) {/** getBytes 默認情況下, 使用的iso8859-1的編碼, 但如果發現碼表中沒有當前字符, * 會使用當前系統下的默認編碼: GBK*/ response.getOutputStream().write("登錄成功".getBytes("utf-8"));} else {response.getOutputStream().write("登錄失敗".getBytes("utf-8"));}}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("doPost");doGet(request, response);}}

    Httpurlconnection實現提交數據到服務器

    public class NetUtils {private static final String TAG = "NetUtils";/*** 使用post的方式登錄* @param userName* @param password* @return*/public static String loginOfPost(String userName, String password) {HttpURLConnection conn = null;try {URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(10000); // 連接的超時時間conn.setReadTimeout(5000); // 讀數據的超時時間conn.setDoOutput(true); // 必須設置此方法, 允許輸出 // conn.setRequestProperty("Content-Length", 234); // 設置請求頭消息, 可以設置多個// post請求的參數String data = "username=" + userName + "&password=" + password;// 獲得一個輸出流, 用于向服務器寫數據, 默認情況下, 系統不允許向服務器輸出內容OutputStream out = conn.getOutputStream(); out.write(data.getBytes());out.flush();out.close();int responseCode = conn.getResponseCode();if(responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(TAG, "訪問失敗: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if(conn != null) {conn.disconnect();}}return null;}/*** 使用get的方式登錄* @param userName* @param password* @return 登錄的狀態*/public static String loginOfGet(String userName, String password) {HttpURLConnection conn = null;try {String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET"); // get或者post必須得全大寫conn.setConnectTimeout(10000); // 連接的超時時間conn.setReadTimeout(5000); // 讀數據的超時時間int responseCode = conn.getResponseCode();if(responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(TAG, "訪問失敗: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if(conn != null) {conn.disconnect(); // 關閉連接}}return null;}/*** 根據流返回一個字符串信息* @param is* @return* @throws IOException */private static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}is.close();String html = baos.toString(); // 把流中的數據轉換成字符串, 采用的編碼是: utf-8// String html = new String(baos.toByteArray(), "GBK");baos.close();return html;} }

    HttpClient實現提交數據到服務器

    public class NetUtils2 {private static final String TAG = "NetUtils";/*** 使用post的方式登錄* @param userName* @param password* @return*/public static String loginOfPost(String userName, String password) {HttpClient client = null;try {// 定義一個客戶端client = new DefaultHttpClient();// 定義post方法HttpPost post = new HttpPost("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");// 定義post請求的參數List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("username", userName));parameters.add(new BasicNameValuePair("password", password));// 把post請求的參數包裝了一層.// 不寫編碼名稱服務器收數據時亂碼. 需要指定字符集為utf-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");// 設置參數.post.setEntity(entity);// 設置請求頭消息 // post.addHeader("Content-Length", "20");// 使用客戶端執行post方法HttpResponse response = client.execute(post); // 開始執行post請求, 會返回給我們一個HttpResponse對象// 使用響應對象, 獲得狀態碼, 處理內容int statusCode = response.getStatusLine().getStatusCode(); // 獲得狀態碼if(statusCode == 200) {// 使用響應對象獲得實體, 獲得輸入流InputStream is = response.getEntity().getContent();String text = getStringFromInputStream(is);return text;} else {Log.i(TAG, "請求失敗: " + statusCode);}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown(); // 關閉連接和釋放資源}}return null;}/*** 使用get的方式登錄* @param userName* @param password* @return 登錄的狀態*/public static String loginOfGet(String userName, String password) {HttpClient client = null;try {// 定義一個客戶端client = new DefaultHttpClient();// 定義一個get請求方法String data = "username=" + userName + "&password=" + password;HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);// response 服務器相應對象, 其中包含了狀態信息和服務器返回的數據HttpResponse response = client.execute(get); // 開始執行get方法, 請求網絡// 獲得響應碼int statusCode = response.getStatusLine().getStatusCode();if(statusCode == 200) {InputStream is = response.getEntity().getContent();String text = getStringFromInputStream(is);return text;} else {Log.i(TAG, "請求失敗: " + statusCode);}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown(); // 關閉連接, 和釋放資源}}return null;}/*** 根據流返回一個字符串信息* @param is* @return* @throws IOException */private static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}is.close();String html = baos.toString(); // 把流中的數據轉換成字符串, 采用的編碼是: utf-8// String html = new String(baos.toByteArray(), "GBK");baos.close();return html;} }

    在onCreate方法中的調用

    public class MainActivity extends Activity {private EditText etUserName;private EditText etPassword;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUserName = (EditText) findViewById(R.id.et_username);etPassword = (EditText) findViewById(R.id.et_password);}public void doGet(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();new Thread(new Runnable() {@Overridepublic void run() {// 使用get方式抓去數據final String state = NetUtils.loginOfGet(userName, password);// 執行任務在主線程中runOnUiThread(new Runnable() {@Overridepublic void run() {// 就是在主線程中操作Toast.makeText(MainActivity.this, state, 0).show();}});}}).start();}public void doPost(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();new Thread(new Runnable() {@Overridepublic void run() {final String state = NetUtils.loginOfPost(userName, password);// 執行任務在主線程中runOnUiThread(new Runnable() {@Overridepublic void run() {// 就是在主線程中操作Toast.makeText(MainActivity.this, state, 0).show();}});}}).start();} }

    使用runOnUiThread方法,可以在子線程中實現對主線程的操作

    使用android-async-http開源庫方法實現提交數據到服務器 ,使用方法也是將src文件夾中的內容復制到程序中即可

    public class MainActivity2 extends Activity {protected static final String TAG = "MainActivity2";private EditText etUserName;private EditText etPassword;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUserName = (EditText) findViewById(R.id.et_username);etPassword = (EditText) findViewById(R.id.et_password);}public void doGet(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();AsyncHttpClient client = new AsyncHttpClient();String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);client.get("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data, new MyResponseHandler());}public void doPost(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();AsyncHttpClient client = new AsyncHttpClient();RequestParams params = new RequestParams();params.put("username", userName);params.put("password", password);client.post("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet", params, new MyResponseHandler());}class MyResponseHandler extends AsyncHttpResponseHandler {@Overridepublic void onSuccess(int statusCode, Header[] headers,byte[] responseBody) { // Log.i(TAG, "statusCode: " + statusCode);Toast.makeText(MainActivity2.this, "成功: statusCode: " + statusCode + ", body: " + new String(responseBody), 0).show();}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {Toast.makeText(MainActivity2.this, "失敗: statusCode: " + statusCode, 0).show();}} }

    可以看到使用開源框架可以更加簡單,高效,安全的實現相同的效果.

    完成

    總結

    以上是生活随笔為你收集整理的Android之网络编程的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。