与服务器进行数据Android--->servlet(get、post、AsyncClient)三种方式


Android端:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <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="loginAsyncHttpClient"
        />
</LinearLayout>


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);
    }
	
      //第一种:get	
    public void loginGet(View view){
       String uname=et_main_uname.getText().toString();
       String upass=et_main_upass.getText().toString();
       String path="http://193.168.2.141:7788/G160628_Server/login.do";
      new MyGetTask().execute(uname,upass,path);
    }


    class MyGetTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] params) {
            String uname=params[0].toString();
            String upass=params[1].toString();
            String path=params[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();
        }
    }

 	//第二种:post	
    public void loginPost(View view){
       String uname=et_main_uname.getText().toString();
       String upass=et_main_upass.getText().toString();
       String path="http://193.168.2.141:7788/G160628_Server/login.do";
      new MyPostTask().execute(uname,upass,path);
    }

    class MyPostTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {
            String uname=params[0].toString();
            String upass=params[1].toString();
            String path=params[2].toString();
            try {
                URL url=new URL(path);
                HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(5000);

                //admin 123
                //uname=admin&upass=123456

                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,s, Toast.LENGTH_SHORT).show();

        }
    }

       //第三种:AsycnClient(需要导jar包:android-async-http-1.4.4.jar,并且进行网络配置)	
    public void loginAsyncHttpClient(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();
        String path="http://193.168.2.141:7788/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);
            }

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

    }

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zking.administrator.g160628_android32_commitdata">

	<!--网络配置-->
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
服务器端:

<%@ page language="java" contentType="text/html; charset=UTf-8"
    pageEncoding="UTf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTf-8">
<title>Insert title here</title>
</head>
<body>
	<h1>登录页面</h1>
	<form action="login.do" method="post">
		用户名:<input type="text" name="uname"/><br/>
		密码:<input type="password" name="upass"/><br/>
		<input type="submit" value="登录"/><br/>
	</form>
</body>
</html>
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();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值