【Android-網絡通信】 客戶端與.Net服務端Http通信

以登錄系統爲例:

1、建立服務端程序

一、打開VS2012,新建項目,建立ASP.NET WEB應用程序 ,命名爲MyApphtml

二、添加新建項,選擇通常處理程序,建立Login.ashxjava

 

C# Code:  Login.ashxandroid

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyApp.Remote
{
    /// <summary>
    /// Login 的摘要說明
    /// </summary>
    public class Login : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            switch (context.Request["type"]) { case "login": loginValidate(context); break; default: break; }
        }

        /// <summary>
        /// 驗證登錄 /// </summary>
        /// <param name="context"></param>
        private void loginValidate(HttpContext context) { string account = context.Request["Account"].ToString(); string password = context.Request["Password"].ToString(); if (account == "123" && password == "123") { string realName="HelloWord"; context.Response.Write("{\"Result\":\"1\",\"RealName\":\""+realName+"\"}"); //實際輸出:{"Result":"1","RealName":"HelloWord"} //注意:雙引號須要用轉義符\
 } else { context.Response.Write("{\"Result\":\"0\"}"); } } public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

三、到這裏就完成服務端的驗證代碼登錄了。apache

瀏覽器輸入地址訪問:http://localhost:11946/Remote/Login.ashx?type=login&Account=123&Password=123  json

四、這時候程序尚未部署到IIS,那麼如何在VS調試的時候,客戶端能夠經過IP訪問該程序?數組

 客戶端經過IP和端口訪問服務端程序瀏覽器

 

2、建立客戶端程序

一、界面佈局 layout \ activity_main.xml服務器

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="10dp"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="帳號" />

        <EditText
            android:id="@+id/edittext_loginAccount"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="number" >

            <requestFocus />
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="密碼" />

        <EditText
            android:id="@+id/editetext_loginPassword"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPassword" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >

        <CheckBox
            android:id="@+id/checkbox_remindPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="記住密碼" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >

        <Button
            android:id="@+id/button_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登陸" />
    </LinearLayout>

</LinearLayout>

二、Java Code : MainActivity.java網絡

package com.example.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private String ServerUrl = "http://192.168.137.210:11946/Remote/";
    private EditText et_loginAccount;
    private EditText et_loginPassword;
    private CheckBox cb_remindPassword;
    private Button btn_login;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

        et_loginAccount = (EditText) findViewById(R.id.edittext_loginAccount);
        et_loginPassword = (EditText) findViewById(R.id.editetext_loginPassword);
        cb_remindPassword = (CheckBox) findViewById(R.id.checkbox_remindPassword);
        btn_login = (Button) findViewById(R.id.button_login);

        btn_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // loading 對話框
                progressDialog = ProgressDialog.show(MainActivity.this, "", "服務器鏈接中...", true, false);
                // 開啓線程去驗證登陸
                new Thread() { @Override public void run() { // 向handler發消息
                        mHandler.sendEmptyMessage(0); } }.start();
            }
        });

    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // 登陸驗證
 loginValidate();
        }

    };

    private void loginValidate() {
        // 打開網絡鏈接
        HttpClient client = new DefaultHttpClient();
        StringBuilder builder = new StringBuilder();
        // 服務器提交地址
        String url = ServerUrl + "Login.ashx?type=login&Account=" + et_loginAccount.getText().toString() + "&Password=" + et_loginPassword.getText().toString();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            // 填充數據流
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                builder.append(s);
            }
            // 讀取Json返回數組
            JSONObject jsonObject = new JSONObject(builder.toString());
            String re_result = jsonObject.getString("Result");
            String re_realName = jsonObject.getString("RealName");
            if (re_result.equals("1")) {
                Toast.makeText(MainActivity.this, "驗證成功!" + re_realName, Toast.LENGTH_SHORT).show();
                // TODO:跳轉頁面
            } else {
                Toast.makeText(MainActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
            }
            progressDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "服務器數據讀取失敗", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
        }
    }

}

 

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());多線程

 少了上面兩句代碼會報錯android.os.NetworkOnMainThreadException即,在主線程訪問網絡時出的異常

Android在4.0以前的版本支持在主線程中訪問網絡,可是在4.0之後對這部分程序進行了優化,也就是說訪問網絡的代碼不能寫在主線程中了。

稍後研究多線程

三、別放了加上權限 AndroidManifest.xml

  <!-- sd卡讀取權限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <!-- 訪問網絡權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- 徹底退出程序權限 -->
    <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
相關文章
相關標籤/搜索