get方式和post方式的区别:

1.请求的URL地址不同:
  post:"http://xx:8081//servlet/LoginServlet"
  get:http://xxx:8081//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://xx:8081");

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

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

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

登录的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.yb.myapplication.MainActivity"> <EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/input_username"
android:hint="@string/input_username"/> <EditText
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:inputType="textPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/input_password"
android:hint="@string/input_password"/> <RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cb_rem"
android:text="@string/reme_password"/> <Button
android:layout_marginRight="30dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt_login"
android:text="@string/bt_login"/>
</RelativeLayout>
</LinearLayout>

登录的Activity代码

public class GetPostActivity extends AppCompatActivity {
private EditText et_username;
private EditText et_password;
private CheckBox cb_rem;
private Button bt_login;
private Context mcontext;
private String username;
private String password;
private boolean isRem; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_post); et_username = (EditText) findViewById(R.id.input_username);
et_password = (EditText) findViewById(R.id.input_password);
cb_rem = (CheckBox) findViewById(R.id.cb_rem);
bt_login = (Button) findViewById(R.id.bt_login);
bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});
} //创建一个handler
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
boolean isloginsuccess = (boolean) msg.obj; if (isloginsuccess) {
//判断是否记住密码,要保存到本地,封装成方法
if (isRem) {
//保存用户名和密码
boolean result = UserInfoUtil.saveUserInfo(mcontext, username, password);
if (result) {
Toast.makeText(getApplicationContext(), "用户名和密码保存成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "用户名和密码保存失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
}
}
}; public void login() {
username = et_username.getText().toString().trim();
password = et_password.getText().toString().trim();
isRem = cb_rem.isChecked();
//判断是否密码或者用户名为空
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
return;
} //post方法登录是否成功
LoginHttpUtil.requestNetForGetLogin(handler, username, password);
}
}

新建一个Net包,处理网络请求的操作,新建一个loginhttputil.java

public class LoginHttpUtil {
//get方式登录
public static void requestNetForGetLogin(final Handler handler,final String username,final String password) { //在子线程中操作网络请求
new Thread(new Runnable() {
@Override
public void run() {
//urlConnection请求服务器,验证
try {
//1:url对象
URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet?username=" + URLEncoder.encode(username)+ "&pwd=" + URLEncoder.encode(password) + "");
//2;url.openconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
//4
int code = conn.getResponseCode();
if (code == 200) {
InputStream inputStream = conn.getInputStream();
String result = StreamUtil.stremToString(inputStream);
System.out.println("=====================服务器返回的信息::" + result);
boolean isLoginsuccess=false;
if (result.contains("success")) {
isLoginsuccess=true;
}
Message msg = Message.obtain();
msg.obj=isLoginsuccess;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} //post方式登录
public static void requestNetForPOSTLogin(final Handler handler,final String username,final String password) {
new Thread(new Runnable() {
@Override
public void run() {
//urlConnection请求服务器,验证
try {
//1:url对象
URL url = new URL("http://192.168.1.100:8081//servlet/LoginServlet"); //2;url.openconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //3设置请求参数
conn.setRequestMethod("POST");
conn.setConnectTimeout(10 * 1000);
//请求头的信息
String body = "username=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(password);
conn.setRequestProperty("Content-Length", String.valueOf(body.length()));
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setRequestProperty("Origin", "http://192.168.1.100:8081"); //设置conn可以写请求的内容
conn.setDoOutput(true);
conn.getOutputStream().write(body.getBytes()); //4响应码
int code = conn.getResponseCode();
if (code == 200) {
InputStream inputStream = conn.getInputStream();
String result = StreamUtil.stremToString(inputStream);
System.out.println("=====================服务器返回的信息::" + result);
boolean isLoginsuccess=false;
if (result.contains("success")) {
isLoginsuccess=true;
}
Message msg = Message.obtain();
msg.obj=isLoginsuccess;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}

二:get方式提交数据时候出现乱码的情况l;解决办法如下:

  一般在开发客户端和服务端的编码要保持一致。

    android端的默认编码是utf-8;

    做url请求时需要对参数进行URLEncode编码.

    URL url = new URL("http://xx:8081/servlet/LoginServlet?username="+URLEncoder.encode(username)+"&pwd="+URLEncoder.encode(password))

# 2.   post方式提交数据乱码解决
  

  String body = "username=" + URLEncoder.encode(username) + "&pwd=" + URLEncoder.encode(password);

android 之HttpURLConnection的post,get方式请求数据的更多相关文章

  1. post方式请求数据

    post方式请求数据 分析: 1.将请求方式改成post conn.setRequestMethod("POST"); 2.设置连接可以输出 conn.setDoOutput(tr ...

  2. get和post方式请求数据,jsonp

    get方式请求数据: p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 19.0px Consolas; color: #289c97 } p.p2 { ma ...

  3. Android学习之Http使用Post方式进行数据提交(普通数据和Json数据)

    转自:http://blog.csdn.net/wulianghuan/article/details/8626551 我们知道通过Get方式提交的数据是作为Url地址的一部分进行提交,而且对字节数的 ...

  4. Android客户端采用Http 协议Post方式请求与服务端进行数据交互(转)

    http://blog.csdn.net/javanian/article/details/8194265

  5. Android HttpClient框架get和post方式提交数据(非原创)

    1.fragment_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android& ...

  6. JAVA通过HTTP方式获取数据

    测试获取免费天气数据接口:http://www.weather.com.cn/data/sk/101190408.html URL数据如下图: 代码部分: package https; import ...

  7. C# http请求数据

    http中get和post请求的最大区别:get是通过URL传递表单值,post传递的表单值是隐藏到 http报文体中 http以get方式请求数据 /// <summary> /// g ...

  8. region URL请求数据

    #region URL请求数据 /// <summary> /// HTTP POST方式请求数据 /// </summary> /// <param name=&quo ...

  9. [Android]解决3gwap联网失败:联网请求在设置代理与直连两种方式的切换

    [Android]解决3gwap联网失败:联网请求在设置代理与直连两种方式的切换 问题现象: 碰到一个问题,UI交互表现为:联通号码在3gwap网络环境下资源一直无法下载成功. 查看Log日志,打印出 ...

随机推荐

  1. VC 鼠标滚轮事件控制绘图的问题

    问题描述: 在MFC中绘制数据曲线,通过鼠标滚轮来进行放大缩小操作.在使用滚轮事件时,发现如果数据量较大,会出现卡顿. 解决方案: 鼠标滚轮事件会进行重复绘图,考虑在鼠标滚轮结束之后再重绘: 在鼠标滚 ...

  2. js三级地区联动

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head ...

  3. [Project Name] was compiled with optimization - stepping may behave oddly; variables may not be available.

    控制台输出的时候显示一串这样的信息:[Project Name] was compiled with optimization - stepping may behave oddly; variabl ...

  4. ftp org.apache.commons.net.ftp.FTPClient 判断文件是否存在

    String path = "/SJPT/ONPUT/HMD_TEST/" ; FtpTool.getFTPClient().changeWorkingDirectory(path ...

  5. css框架

    框架:如果你想在一个页面里面,嵌入另一个页面,就可以使用框架了. 框架分为两种: 一.iframe标签: 本页面中再嵌入另一个网页. iframe标签:浮动的框架,嵌入页面使用. 可以直接写在body ...

  6. R语言 入门知识--常用操作和例子

    1 R的下载.安转   (转)R有很多的版本,支持目前主流的操作系统MAC.Linux和WINDOWS系列.因为我个人是在WINDOWS下用R的,所以在这里将只介绍WINDOWS下R的下载&安 ...

  7. 2014ACM/ICPC亚洲区北京站

    1001  A Curious Matt 求一段时间内的速度单位时间变化量,其实就是直接求出单位时间内的,如果某段时间能达到最大那么这段时间内必定有一个或一小段单位时间内速度变化是最大的即局部能达到最 ...

  8. 协议分析TMP

    最近闲来有事, 分析了一个非常低端(非常低端的意思是说你不应该对她是否能取代你现有的QQ客户端作任何可能的奢望,她只是一个实验性的东西)的手机QQ的协议, 是手机QQ3.0,      所用到的TCP ...

  9. Knockout.js随手记(8)

    visible, disable, css绑定 这个例子非常简单,主要演示如何通过属性控制html元素的显示与否(visible),可用性(disable)以及根据属性添加相应的CSS样式. 先简单的 ...

  10. MachineKey 操作 之 获取 MachineKey

    MachineKey获取介绍 对MachineKey进行配置,以便将其用于对 Forms 身份验证 Cookie 数据和视图状态数据进行加密和解密,并将其用于对进程外会话状态标识进行验证.本次讲的是如 ...