一、get方式提交和post方式提交区别
1.区别
get方式:组拼url地址,把数据组拼到url上 有大小限制,浏览器规定:1kb http规定:4kb
post方式:数据安全,没有大小限制
路径不同 2.post方式要自己组拼请求体的内容 3.post方式比get方式多了两个头信息:content-length、content-type
2.get方式提交数据到服务器(之前写的均为get方式)
3.post方式提交数据到服务器
public void click2(View v){
new Thread(){
@Override
public void run() {
try {
String name = et_name.getText().toString().trim();
String psw = et_psw.getText().toString().trim();
//区别1:路径不同
//String path = "http://192.168.11.86:8080/news.xml";
String path = "http://192.168.11.73:8080/login/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//区别2:请求方式不同
//conn.setRequestMethod("GET");
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
//区别3:要多设置两个请求头信息
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); //通过抓包工具获取HttpWatch
String data = "username="+name+"&password="+psw+""; //设置请求体
conn.setRequestProperty("Content-Length",data.length()+"");
//区别4:post方式要将组拼好的数据交给服务器 以流的形式提交
conn.setDoOutput(true); //设置一个标记,允许输出
conn.getOutputStream().write(data.getBytes());
int code = conn.getResponseCode();
if(code == 200){
InputStream in = conn.getInputStream();
final String content = StreamTools.readStream(inputStream);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,content,Toast.LENGTH_SHORT).show();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
二、乱码问题
1.服务器在返回中文时,在Android上弹得Toast为乱码
原因,编码方式不同
处理方式:
1)在服务器中更改编码方式
response.getOutputStream().write("成功".getBytes("utf-8")); //将服务器编码方式改为utf-8
2)在Android工程中更改解码方式
String content = new String(baos.toByteArray(),"gbk"); //更改解码方式为gbk
2.往服务器提交中文
1)在服务器中先通过iso-8859-1编码,在通过utf-8进行解码
2)在Android中对中文先进行一个url的编码
String data = "username="+URLEncoder.encode(name,"utf-8")
+"&password="+URLEncoder.encode(psw,"utf-8")+""; //封装好的api