前面的文章中,我们曾经实现了一个HTTP的GET 和 POST 请求;
此处我封装了一个HTTP的get和post的辅助类,能够更好的使用;
类名:HttpRequestUtil
提供的方法:
(1) public static URLConnection sendGetRequest(String url,Map<String, String> params, Map<String, String> headers)
参数:
(1)url:单纯的URL,不带任何参数;
(2)params:参数;
(3)headers:需要设置的HTTP请求头;
返回:
HttpURLConnection
(2)public static URLConnection sendPostRequest(String url,Map<String, String> params, Map<String, String> headers)
参数:
(1)url:单纯的URL,不带任何参数;
(2)params:参数;
(3)headers:需要设置的HTTP请求头;
返回:
HttpURLConnection
package com.xiazdong.network.http.util;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HttpRequestUtil {
public static URLConnection sendGetRequest(String url,
Map<String, String> params, Map<String, String> headers)
throws Exception {
StringBuilder buf = new StringBuilder(url);
buf.append("?");
Set<Entry<String, String>> entrys = params.entrySet();
for (Map.Entry<String, String> entry : entrys) {
buf.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
.append("&");
}
buf.deleteCharAt(buf.length() - 1);
URL url1 = new URL(buf.toString());
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("GET");
if (headers != null) {
entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.getResponseCode();
return conn;
}
public static URLConnection sendPostRequest(String url,
Map<String, String> params, Map<String, String> headers)
throws Exception {
StringBuilder buf = new StringBuilder();
Set<Entry<String, String>> entrys = params.entrySet();
for (Map.Entry<String, String> entry : entrys) {
buf.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
.append("&");
}
buf.deleteCharAt(buf.length() - 1);
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(buf.toString().getBytes("UTF-8"));
if (headers != null) {
entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.getResponseCode(); // 为了发送成功
return conn;
}
}
此后,像前面文章中的例子,我们可以很简单的通过如下方式实现:
Map<String,String> params = new HashMap<String,String>();
params.put("name", name.getText().toString());
params.put("age", age.getText().toString());
HttpURLConnection conn = (HttpURLConnection) HttpRequestUtil.sendGetRequest("http://192.168.0.103:8080/Server/PrintServlet", params, null);
简单了很多,对吧?