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:理论无限制
需要注意的是在清单中添加权限
客户端代码
<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>
根据不同的需求选择不同的请求
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>
根据不同的需求选择不同的请求
相关文章推荐
- 12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,
- 12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,
- Android的Http通信加载页面、下载图片 以及doGet、doPost请求服务器
- Android普通方式的DoPost请求提交数据
- android doGet和doPost
- 请求一个url 获得返回结果(doPost doGet方式)
- android doGet和doPost
- 【Android基础知识】HttpUrlConnection使用doGet和doPost方式和服务器交互
- android doGet和doPost
- httpclient的dopost和doget请求
- HttpClient doPost doGet 请求 返回内存流
- JavaWeb-3 Servlet之doGet doPost请求&生命周期简述
- Servlet学习笔记(一)--HttpServlet实现doGet和doPost请求的原理
- Servlet--HttpServlet实现doGet和doPost请求的原理
- 什么时候会调用doGet,doPost ?哪些是get请求?get的特点?哪些是post请求?post请求的特点?
- okHttp拦截器放在doGet和doPost请求中
- 小白胡说:Servlet中doGet和doPost两种请求方式的区别
- servlet中doGet和doPost字符乱码问题
- Android发送HTTP POST请求示范
- WEB应用中的servlet的 service,doPost,doGet方法的关系