您的位置:首页 > 移动开发 > Android开发

android doGet和doPost请求

2016-09-25 00:35 351 查看
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>


根据不同的需求选择不同的请求
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: