android doGet和doPost请求

get方式提交数据到服务器和post方式提交数据到服务器的区别

1.请求的URL地址不同:
            post:"http://192.168.13.83:8080/itheima74/servlet/LoginServlet"
            get:http://192.168.13.83:8080/itheima74/servlet/LoginServlet?username=root&pwd=123

        2.请求头不同:
            ****post方式多了几个请求头:Content-Length   Cache-Control  Origin

            openConnection.setRequestProperty("Content-Length", body.length()+"");
            openConnection.setRequestProperty("Cache-Control", "max-age=0");
            openConnection.setRequestProperty("Origin", "http://192.168.13.83:8080");

            ****post方式还多了请求的内容:username=root&pwd=123

                //设置UrlConnection可以写请求的内容
            openConnection.setDoOutput(true);
            //获取一个outputstream,并将内容写入该流
            openConnection.getOutputStream().write(body.getBytes());

        3.请求时携带的内容大小不同
            get:1k 
            post:理论无限制

需要注意的是在清单中添加权限

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

客户端代码

<span style="font-size:14px;">package com.example.doget_dopost;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by ls on 2016/9/24.
 */
public class HttpRequestActivity  extends Activity{

    private static final String TAG = "HttpRequestActivity";

    EditText nameEditText=null;
    EditText pwdEditText=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);
        nameEditText = (EditText) findViewById(R.id.name);
        pwdEditText = (EditText) findViewById(R.id.key);
    }

    //get请求
    public void loginGet(View view) {
        String name = nameEditText.getText().toString();
        String pwd = pwdEditText.getText().toString();

        final String address =  "http://192.168.1.103:8080/itheima74/servlet/LoginServlet?username="+name+"&pwd="+pwd;

       new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   URL url = new URL(address);
                   HttpURLConnection connection =(HttpURLConnection) url.openConnection();
                   connection.setRequestMethod("GET");
                   connection.setConnectTimeout(2000);
                   int code = connection.getResponseCode();
                   if (code == 200) {
                       InputStream is =  connection.getInputStream();
                       String result = Stream2StringUtils.stream2String(is);
                       Log.d(TAG, "login:  ==="+result);
                   }
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }).start();

    }

    //post请求
    public void loginPost(View view) {
        String name = nameEditText.getText().toString();
        String pwd = pwdEditText.getText().toString();

        final String address =  "http://192.168.1.103:8080/itheima74/servlet/LoginServlet";
        final String body = "username="+name+"&pwd="+pwd;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(address);
                    HttpURLConnection connection =(HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(2000);
                   <span style="color:#FF6600;"> //在get的基础上
                    // 1添加请求头
                    connection.setRequestProperty("Content-Length",body.length()+"");
                    connection.setRequestProperty("Cache-Control","max-age=0");
                    connection.setRequestProperty("Origin","http://192.168.1.103:8080");
                    //2设置connection可以请求的内容
                    connection.setDoOutput(true);
                    //3 获取一个outputStream将内容写入该流
                    connection.getOutputStream().write(body.getBytes());</span>

                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream is =  connection.getInputStream();
                        String result = Stream2StringUtils.stream2String(is);
                        Log.d(TAG, "login:  ==="+result);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


}</span>

输入流转自定义编码的工具类 Stream2StringUtils

<span style="font-size:14px;">package com.example.doget_dopost;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by ls on 2016/9/24.
 * doGet请求和doPost请求
 */
public class Stream2StringUtils {


    public static String stream2String(InputStream is) {

        //返回一个字节数组写入流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int size = 0;
        String retValue = "";
        try {
            while ((size = is.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
            retValue = new String(bos.toByteArray(), "gbk");
        } catch (IOException e) {
            e.printStackTrace();
        }


        return retValue;
    }

}</span>

服务器端

<span style="font-size:14px;">package com.itheima.service;

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;

public class LoginServlet extends HttpServlet {

	public LoginServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		
		System.out.println("username:"+username);
		System.out.println("password:"+pwd);
		if(username != null && !"".equals(username) && pwd != null && !"".equals(pwd)){
			
			if(username.equals("root") && pwd.equals("123")){
				response.getOutputStream().write("成功".getBytes());  //gbk编码
			}else{
				response.getOutputStream().write("失败".getBytes());	
			}
			
		}else{
			response.getOutputStream().write("login fail; username or password is null".getBytes());	
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public void init() throws ServletException {
	}

}</span>

layout布局

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="登录名"
         />
    <EditText
        android:id="@+id/key"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="登录密码"
        />
    <Button
        android:onClick="loginGet"
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Get登录"
        />

    <Button
        android:layout_marginTop="50dp"
        android:onClick="loginPost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Post登录"
        />
</LinearLayout></span>

根据不同的需求选择不同的请求


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独步秋风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值