Android 使用HTTP(get和post)方式登陆服务器
package com.wuyou.submittoserver; import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder; public class MainActivity extends ActionBarActivity { private static final int OK = 200;
private EditText usernameEditText;
private EditText passwrodEditText; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); usernameEditText = (EditText) findViewById(R.id.username);
passwrodEditText = (EditText) findViewById(R.id.password);
} /**
* post方法多了三个东西:
* ①请求的表单类型
* ②请求的数据长度
* ③请求的数据并且写给服务器
*/
public void post(View view) {
final String username = usernameEditText.getText().toString().trim();
final String password = passwrodEditText.getText().toString().trim();
//Android默认模拟器外部的地址为10.0.2.2,而不是localhost和127.0.0.1
final String serverPath = "http://10.0.2.2:8080/LoginServlet";
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
//给出提示:账号密码不许为空
} else {
new Thread(new Runnable() {
@Override
public void run() {
try {
//向服务器请求的数据
String data = "username=" + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
URL url = new URL(serverPath);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoOutput(true);//打开输出流,以便向服务器提交数据
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data.getBytes()); int responseCode = httpURLConnection.getResponseCode();
if (200 == responseCode) {
InputStream inputStream = httpURLConnection.getInputStream();
final String responseMsg = StreamTool.getString(inputStream);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, responseMsg, Toast.LENGTH_LONG).show();
}
});
} else {
System.out.println("responseCode = " + responseCode);
//连接服务器出错,错误代码为:responseCode 根据代码值告诉用户出错的原因
//....
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
} public void get(View view) {
final String username = usernameEditText.getText().toString().trim();
final String password = passwrodEditText.getText().toString().trim();
//Android默认模拟器外部的地址为10.0.2.2,而不是localhost和127.0.0.1
final String serverPath = "http://10.0.2.2:8080/LoginServlet";
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
//给出提示:账号密码不许为空
} else {
new Thread(new Runnable() {
@Override
public void run() {
try {
//使用GET方式请求服务器只能这样
URL url = new URL(serverPath + "?username=" + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8"));
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
int responseCode = httpURLConnection.getResponseCode();
if (200 == responseCode) {
InputStream inputStream = httpURLConnection.getInputStream();
final String responseMsg = StreamTool.getString(inputStream);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, responseMsg, Toast.LENGTH_LONG).show();
}
});
} else {
System.out.println("responseCode = " + responseCode);
//连接服务器出错,错误代码为:responseCode 根据代码值告诉用户出错的原因
//....
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
} class StreamTool {
public static String getString(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length;
while((length = inputStream.read(buf)) >0) {
byteArrayOutputStream.write(buf, 0 ,length);
}
byte[] stringBytes = byteArrayOutputStream.toByteArray();
String str = new String(stringBytes);
return str;
}
}
界面就不写了。
要注意几个地方:
①模拟器访问本机服务器127.0.01(locahost)的话,使用的地址是:10.0.2.2
②post比get方法多了三个要发送的数据头(header)
Android 使用HTTP(get和post)方式登陆服务器的更多相关文章
- Android客户端与服务端交互之登陆示例
Android客户端与服务端交互之登陆示例 今天了解了一下android客户端与服务端是怎样交互的,发现其实跟web有点类似吧,然后网上找了大神的登陆示例,是基于IntentService的 1.后台 ...
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (一) —— 总览
Android数据的四种存储方式SharedPreferences.SQLite.Content Provider和File (一) —— 总览 作为一个完成的应用程序,数据存储操作是必不可少的. ...
- Android网络之数据解析----SAX方式解析XML数据
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...
- Android通过http协议POST传输方式
Android通过http协议POST传输方式如下: 方式一:HttpPost(import org.apache.http.client.methods.HttpPost) 代码如下: privat ...
- Android 连接 SQL Server (jtds方式)——上
本文将介绍开发Android程序,连接SQL Server,通过第三方包jtds的方式. 如果你有同样的需求,请跟着做一遍,博主将以最详细的方式,进行介绍. 首先说明,Java.Android连接SQ ...
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences
除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息.其存储位置在/data ...
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (四) —— ContentProvider
ContentProvider是安卓平台中,在不同应用程序之间实现数据共享的一种机制.一个应用程序如果需要让别的程序可以操作自己的数据,即可采用这种机制.并且此种方式忽略了底层的数据存储实现,Cont ...
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite
SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是: NULL: 空值 INTEGER: 整数 REAL: 浮点数 TEXT: 字符串 BLOB: 大数据 在SQLite中, ...
- Android中日志信息的打印方式
Android中日志信息的打印方式主要有以下7种: 1)System.out(i级别) 2)System.err(w级别) 3)Log.v 4)Log.d 5)Log.i 6)Log.w 7)Log. ...
随机推荐
- ccrendertexture
int bgHeight=150; CCSprite *sp=CCSprite::create("HelloWorld.png"); sp->setAnchorPoint(c ...
- QT开发pjsip的VOIP,A8平台运行
QT开发pjsip的VOIP 开发环境 平台:A8 环境:Linux-3.0.8 实现功能:使用QT开发VOIP进行初始化.拨号.挂起 测试工具:minisipserver服务器 效果 界面: min ...
- ARCGIS获取图层下的要素信息及要素类转换为要素
/// <summary> /// 得到需要的字段名和字段值 /// </summary> /// <param name="layer">&l ...
- Base64算法
为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/4288372.html ...
- 多线程、Socket
多线程 线程.进程和应用程序域 进程:进程是一个操作系统上的概念,用来实现多任务并发执行,是资源分配的最小单元,各个进程是相互独立的,可以理解为执行当中的程序,在操作系统中一般用一个称为PCB的结 ...
- iOS,长按图片保存实现方法,轻松搞定!
1.添加手势识别: UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@s ...
- java封装和多态
封装.集成.多态和抽象是java的基本特征. 封装的第一步就是对类进行组装,即定义一个类,这时候要考虑这个类要有哪些属性.方法等.第二步就是信息的隐藏,这包括访问修饰符.get/set方法和某些特定方 ...
- [LeetCode OJ] Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is ...
- c语言的数组指针与指针数组
1. 数组指针:指向数组的指针是数组指针 先看下面一段代码: #include <stdio.h> int main(void) { int m[10]; printf("m = ...
- jQuery动态添加的元素中处理字符串溢出后在指定字符数后添加省略号
"+[jsonData[i].questitle.lenth>40?jsonData[i].questitle.substring(0,40)+"...":json ...