提交数据的三种方式

1.get post  AsyncHttpClient这三种与后台相接的方式


2.例子:login

1.web后台(服务端):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>登录</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <form action="login.do" method="post">
    	用户名:<input type="text" name="uname"/><br/>
    	密码:<input type="password" name="upass"/><br/>
    	<input type="submit" value="登录"/>
    </form>
  </body>
</html>
servlet:

package com.zking.servlet;

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;

/**
 *@author 
 *@date  2017-7-27 下午08:33:34
 */
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");
		String s=null;
		if("admin".equals(uname)&&"123".equals(upass)){
			s="success";
		}else{
			s="fail";
		}
		
		PrintWriter pw=resp.getWriter();
		pw.write(s);
		pw.close();
	}

}

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>loginServlet</servlet-name>
  	<servlet-class>com.zking.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>loginServlet</servlet-name>
  	<url-pattern>/login.do</url-pattern>
  </servlet-mapping>
</web-app>

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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.zking.async.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"
        android:gravity="center"
        android:textSize="30sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入用户名"
        android:id="@+id/main_uname"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入密码"
        android:id="@+id/main_upass"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:onClick="getData"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:onClick="postData"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:onClick="anyscData"/>


</LinearLayout>

注意配置:网络权限   
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

activity:

package com.zking.async;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private EditText main_uname;
    private EditText main_upass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        main_uname = (EditText) findViewById(R.id.main_uname);
        main_upass = (EditText) findViewById(R.id.main_upass);
    }

    public void getData(View view){
           String uname= main_uname.getText().toString();
           String upass=main_upass.getText().toString();
           String path="http://193.168.4.232:8080/test/login.jsp";
           new MyGetData().execute(uname,upass,path);
    }

    public void postData(View view){
        String uname= main_uname.getText().toString();
        String upass=main_upass.getText().toString();
        String path="http://193.168.4.232:8080/test/login.jsp";
        new MyPostData().execute(uname,upass,path);
    }

    public void anyscData(View view){
        String uname= main_uname.getText().toString();
        String upass=main_upass.getText().toString();
        String path="http://193.168.4.232:8080/test/login.jsp";
        AsyncHttpClient asc=new AsyncHttpClient();
        RequestParams rp=new RequestParams();
        rp.put("uname",uname);
        rp.put("upass",upass);

        asc.post(this,path,rp,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 MyPostData 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 h= (HttpURLConnection) url.openConnection();
                h.setRequestMethod("POST");
                h.setConnectTimeout(5000);
                //设置请求头
                //添加请求头
                String s="uname="+uname+"&upass="+upass;
                h.setRequestProperty("Content-Length",s.length()+"");
                h.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                h.setDoOutput(true);//对外输出数据
                OutputStream os= h.getOutputStream();
                os.write(s.getBytes());
                Toast.makeText(MainActivity.this, "safa", Toast.LENGTH_SHORT).show();
                if(h.getResponseCode()==200){
                    Toast.makeText(MainActivity.this, "进来", Toast.LENGTH_SHORT).show();
                    InputStream is=h.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();
        }
    }


    class MyGetData 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 httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setConnectTimeout(5000);
                if(httpURLConnection.getResponseCode()==200){
                    InputStream is=httpURLConnection.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String s=br.readLine();
                    Log.i("test",s);
                    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();
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值