android 向服务器提交数据(get-post-AsyncHttpClient)

在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持。

  在HTTP通信中使用最多的就是GET和POST了,GET请求可以获取静态页面,也可以把参数放在URL字符串的后面,传递给服务器。POST与GET的不同之处在于POST的参数不是放在URL字符串里面,而是放在HTTP请求数据中。

清单文件里面要加入网络权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

下面代码实例:

public class MainActivity extends AppCompatActivity {

    private EditText et_main_uname;
    private EditText et_main_upass;
    private URL url;
    private HttpURLConnection httpURLConnection;

    @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();
        new MyTask().execute(uname,upass,"GET");
    }

    //使用post提交
    public void loginPOST(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();
        new MyTask().execute(uname,upass,"POST");
    }

    //使用第三方AsyncHttpClient提交
    //HttpClient导致不可以问题,在Gradle android{}里面加入一个内库useLibrary 'org.apache.http.legacy'(复制进去即可)

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

        AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
        RequestParams requestParames=new RequestParams();
        requestParames.put("uname",uname);
        requestParames.put("upass",upass);
        asyncHttpClient.post("http://192.168.10.101:8080/androidData/doIndex.do",requestParames,new TextHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, String responseBody) {
                super.onSuccess(statusCode, headers, responseBody);
                Toast.makeText(MainActivity.this, ""+responseBody, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, org.apache.http.Header[] headers, String responseBody, Throwable error) {
                super.onFailure(statusCode, headers, responseBody, error);
            }
        });

    }

    class MyTask extends AsyncTask{

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

            try {
                if ("GET".equals(type)){
                    //用Get方式请求
                    url = new URL("http://192.168.10.101:8080/androidData/doIndex.do?uname="+uname+"&upass="+upass);
                    Log.i("test","GET方式");
                }else if("POST".equals(type)){
                    url=new URL("http://192.168.10.101:8080/androidData/doIndex.do");
                    Log.i("test","POST方式");
                }
                httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod(type);
                httpURLConnection.setConnectTimeout(5000);

                if ("POST".equals(type)){
                    //设置可以允许对外输出数据
                    httpURLConnection.setDoOutput(true);
                    String str="uname="+uname+"&upass="+upass;
                    //添加请求头
                    //Content-Length:
                    httpURLConnection.setRequestProperty("Content-Length",""+str.length());
                    //Content-Type:application/x-www-form-urlencoded
                    httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    //将内容提交到服务器
                    httpURLConnection.getOutputStream().write(str.getBytes());

                }
                if (httpURLConnection.getResponseCode()==200){
                    InputStream inputStream=httpURLConnection.getInputStream();
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                    String str=bufferedReader.readLine();
                    return str;
                }


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


            return null;
        }

        //更新UI
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            String s= (String) o;
            if ("success".equals(s.trim())){
                Toast.makeText(MainActivity.this, "登录成功,正在跳转", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }

        }
    }


}

xm代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="ghq.zking.com.ghq_android_31.MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_uname"
        android:hint="请输入用户名:"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_upass"
        android:hint="请输入密码:"
        />
    <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 SendDataServlet implements Servlet{

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public ServletConfig getServletConfig() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getServletInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    public void init(ServletConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String uname=request.getParameter("uname").trim();
        String upass=request.getParameter("upass").trim();

        String str=null;

        if("admin".equals(uname)&&"upass".equals(upass)){
            str="success";

        }else{
            str="failure";
        }

        System.out.println("用户名:"+uname+"密码:"+upass);

        request.setAttribute("result", str);
        request.getRequestDispatcher("result.jsp").forward(request, response);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值