您的位置:首页 > 理论基础 > 计算机网络

从头学android_GET 和 POST 网络请求

2016-05-30 23:24 555 查看

表单请求

Post和get请求作为Http请求的两种方式,不管是在web中,还是android中,都是相同的。get请求直接将参数拼接在url后面,post请求将参数作为响应体发送,二者对中文参数都是经过url编码后传输。

get请求

String path = "http://172.20.12.131:8080/web001/LoginServlet?username=" + URLEncoder.encode(username) + "&password=" + password;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);

Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
}
其中
URLEncoder.encode(username)
是一个过时方法,被建议使用的是
URLEncoder.encode(String text,String charSet)


通过查看源码发现

public static String encode(String s) {
return ENCODER.encode(s, StandardCharsets.UTF_8);
}


可见,这个方法虽然过时,但是只是对不过时方法的一次调用,并且直接使用了UTF-8,所以,就应该用这个过时方法。

post请求

String path = "http://172.20.12.131:8080/web001/LoginServlet";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
//拼接响应体内容
String content = "username="+URLEncoder.encode(username)+"&password="+URLEncoder.encode(password);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//自行设置Content-Type
conn.setRequestProperty("Content-Length",content.length()+"");//自行设置Content-Length

conn.setDoOutput(true);//必须设置,标志这个请求要写入内容
OutputStream out = conn.getOutputStream();
out.write(content.getBytes());
out.close();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
String result = getStringFromInputStream(is);
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
}
}



与get不同,post有两个请求头需要自己设置,内容需要用输出流写入。

中文乱码问题:

核心思想是,能选的地方都设置为UTF-8,不能选却要用的地方先用原字符集得到字节流,再用UTF-8 new出新字符串使用。

服务器端乱码处理

/*
* get请求的乱码
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 得到乱码
String name = request.getParameter("username");
// 转换编码
name = new String(name.getBytes("iso-8859-1"), "utf-8");//可以解决!
System.out.println(name);

// 响应乱码
response.setContentType("text/html;charset=utf-8");// 可以解决!
response.getWriter().write("张三");
}
 
/*
* post请求乱码
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
// 请求乱码
request.setCharacterEncoding("utf-8");// 可以解决
String name = request.getParameter("username");
System.out.println(name);
 
// 响应乱码
response.setContentType("text/html;charset=utf-8");// 可以解决!!
response.getWriter().write("李四");
}


客户端乱码处理

1.对于参数要用url编码封装,

2.对于响应流中的数据,用utf-8接收

String(bos.toByteArray(), "utf-8")


总结

这种原始的请求方式虽然在开发中不见得有多么常用,但是理解它的整个过程对使用其他快捷方法有很大的帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: