HttpUtil

1、发送doPost请求,在web那边使用request.setCharacterEncoding("UTF-8");保证中文不乱码,不需要第三方jar包

 1 public static String sendPost(String url, String param) {
 2 PrintWriter out = null;
 3 BufferedReader in = null;
 4 String result = "";
 5 try {
 6     URL realUrl = new URL(url);
 7     // 打开和URL之间的连接
 8     URLConnection conn = realUrl.openConnection();
 9     // 设置通用的请求属性
10     conn.setRequestProperty("accept", "*/*");
11     conn.setRequestProperty("connection", "Keep-Alive");
12     conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
13     conn.setRequestProperty("charset", "utf-8");
14     // 发送POST请求必须设置如下两行
15     conn.setDoOutput(true);
16     conn.setDoInput(true);
17     // 获取URLConnection对象对应的输出流
18     out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
19     // 发送请求参数
20     out.print(param);
21     // flush输出流的缓冲
22     out.flush();
23     // 定义BufferedReader输入流来读取URL的响应
24     in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
25     String line;
26     while ((line = in.readLine()) != null) {
27         result += line;
28     }
29 } catch (Exception e) {
30     System.out.println("发送 POST 请求出现异常!" + e);
31     e.printStackTrace();
32 }
33 // 使用finally块来关闭输出流、输入流
34 finally {
35     try {
36         if (out != null) {
37             out.close();
38         }
39         if (in != null) {
40             in.close();
41         }
42     } catch (IOException ex) {
43         ex.printStackTrace();
44     }
45 }
46 return result;
47 }
View Code

 2、拼装URL参数信息

 1 public static String buildQueryStr(Map<String, Object> params) {
 2     if (CheckNull.isNull(params)) {
 3         return "";
 4     }
 5     StringBuffer sb = new StringBuffer();
 6     for (String k : params.keySet()) {
 7         sb.append(k);
 8         sb.append("=");
 9         sb.append(params.get(k).toString());
10         sb.append("&");
11     }
12     return sb.toString().substring(0, sb.length() - 1);
13 }
View Code
这个博客主要是javaEE相关或者不相关的记录, hadoop与spark的相关文章我写在下面地址的博客啦~ http://www.cnblogs.com/sorco
原文地址:https://www.cnblogs.com/orco/p/6224827.html