使用POST、GET、AsyncHttpClient創造服務端用手機端來連接進行登錄

今天的實現方法比較簡單,就不打太多的註釋了,都是一些死腦筋

首先實現服務器


簡單的登錄界面測試

<form action="login.do" method="post">
		用戶名:<input type="text" name="uname"/><br/>
		密碼:<input type="password" name="upass"/><br/>
		<input type="submit" value="登錄" />
	</form>

登錄的業務邏輯

public class LoginServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//獲取用戶名密碼
		String uname=req.getParameter("uname");
		String upass=req.getParameter("upass");
		System.out.println(uname+"   "+upass);
		
		String result=null;
		//判斷
		if("admin".equals(uname)&&"123".equals(upass)){
			result="success";
		}else{
			result="fail";
		}
		
		
		PrintWriter pw=resp.getWriter();
		pw.write(result);
		pw.close();
		
		
		
	}
	
}

web.xml進行配置

  <servlet>
  	<servlet-name>loginServlet</servlet-name>
  	<servlet-class>com.bihua.Servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>loginServlet</servlet-name>
  	<url-pattern>/login.do</url-pattern>
  </servlet-mapping>



客戶端

簡單的登錄界面,三個測試方法

 <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名"
        android:id="@+id/et_main_uname"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:id="@+id/et_main_upass"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登錄(Get)"
        android:onClick="loginGet"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登錄(Post)"
        android:onClick="loginPost"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登錄(AsyncHttpClient)"
        android:onClick="loginAsynHttpClient"
        />


public class MainActivity extends AppCompatActivity {

    private EditText et_main_uname;
    private EditText et_main_upass;

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

        et_main_uname = (EditText) findViewById(R.id.et_main_uname);
        et_main_upass = (EditText) findViewById(R.id.et_main_upass);


    }

    public void loginGet(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();

        String path="http://192.168.43.107:8080/G160628_Server/login.do";
        new MyGetTask().execute(uname,upass,path);


    }

    public void loginPost(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();

        String path="http://192.168.43.107:8080/G160628_Server/login.do";
        new myPostTask().execute(uname,upass,path);


    }

    public void loginAsynHttpClient(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();

        //path用do接收
        String path="http://192.168.43.107:8080/G160628_Server/login.do";

        AsyncHttpClient ahc=new AsyncHttpClient();
        RequestParams params=new RequestParams();
        params.put("uname",uname);
        params.put("upass",upass);
        ahc.post(this,path,params,new TextHttpResponseHandler(){
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                super.onFailure(statusCode, headers, responseBody, error);
                Toast.makeText(MainActivity.this, ""+responseBody, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                super.onSuccess(statusCode, headers, responseBody);
                Toast.makeText(MainActivity.this, ""+responseBody, Toast.LENGTH_SHORT).show();
            }
        });

    }

    class MyGetTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] objects) {
            String uname=objects[0].toString();
            String upass=objects[1].toString();
            String path=objects[2].toString();

            try {
                URL url=new URL(path+"?uname="+uname+"&upass="+upass);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                if(connection.getResponseCode()==200){
                    InputStream is=connection.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String s=br.readLine();
                    return s;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String s= (String) o;
            Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
        }
    }

    class myPostTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] objects) {
            String uname=objects[0].toString();
            String upass=objects[1].toString();
            String path=objects[2].toString();

            try {
                URL url=new URL(path);
                HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(5000);

                //添加請求頭
                //admin 123
                //uname=admin&upass=123

                String s="uname="+uname+"&upass="+upass;
                conn.setRequestProperty("Content-Length",s.length()+"");
                conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                //允許對外輸出
                conn.setDoOutput(true);

                OutputStream os=conn.getOutputStream();
                os.write(s.getBytes());

                if(conn.getResponseCode()==200){
                    InputStream is=conn.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String str=br.readLine();
                    return str;
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String s= (String) o;
            Toast.makeText(MainActivity.this, ""+o, Toast.LENGTH_SHORT).show();
        }
    }

}

配置獲得網絡權限

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

注意

AsyncHttpClient需要導入jar包
並且在項目對應的.gradle文件中版本號的前面加上
useLibrary 'org.apache.http.legacy'
這一串

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章