java 自带 http get/post 请求
请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.URL; 6 import java.net.URLConnection; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.Set; 10 11 public class HttpRequest { 12 /** 13 * 向指定URL发送GET方法的请求 14 * 15 * @param url 发送请求的URL 16 * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 17 * @return URL 所代表远程资源的响应结果 18 */ 19 public static String sendGet(String url, String param) { 20 String result = ""; 21 BufferedReader in = null; 22 try { 23 String urlNameString = url + "?" + param; 24 URL realUrl = new URL(urlNameString); 25 // 打开和URL之间的连接 26 URLConnection connection = realUrl.openConnection(); 27 // 设置通用的请求属性 28 connection.setRequestProperty("accept", "*/*"); 29 connection.setRequestProperty("connection", "Keep-Alive"); 30 connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 31 // 建立实际的连接 32 connection.connect(); 33 // 获取所有响应头字段 34 Map<String, List<String>> map = connection.getHeaderFields(); 35 // 遍历所有的响应头字段 36 for (String key : map.keySet()) { 37 System.out.println(key + "--->" + map.get(key)); 38 } 39 // 定义 BufferedReader输入流来读取URL的响应 40 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 41 String line; 42 while ((line = in.readLine()) != null) { 43 result += line; 44 } 45 } catch (Exception e) { 46 System.out.println("发送GET请求出现异常!" + e); 47 e.printStackTrace(); 48 } 49 // 使用finally块来关闭输入流 50 finally { 51 try { 52 if (in != null) { 53 in.close(); 54 } 55 } catch (Exception e2) { 56 e2.printStackTrace(); 57 } 58 } 59 return result; 60 } 61 62 /** 63 * 向指定 URL 发送POST方法的请求 64 * 65 * @param url 发送请求的 URL 66 * @param map/param 请求参数 67 * 68 * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 69 * @return 所代表远程资源的响应结果 70 */ 71 public static String sendPost(String url, String param) { 72 // public static String sendPost(String url, Map<String, String> map) { 73 // String param = getKeyVAlueSting(map); //如果是参数是String 就不需要再转换成name1=value1&name2=value2 的形式 74 System.out.println(param); 75 PrintWriter out = null; 76 BufferedReader in = null; 77 String result = ""; 78 try { 79 URL realUrl = new URL(url); 80 // 打开和URL之间的连接 81 URLConnection conn = realUrl.openConnection(); 82 // 设置通用的请求属性 83 conn.setRequestProperty("accept", "*/*"); 84 conn.setRequestProperty("connection", "Keep-Alive"); 85 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 86 // 发送POST请求必须设置如下两行 87 conn.setDoOutput(true); 88 conn.setDoInput(true); 89 // 1.获取URLConnection对象对应的输出流 90 out = new PrintWriter(conn.getOutputStream()); 91 // 2.中文有乱码的需要将PrintWriter改为如下 92 // out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8") 93 // 发送请求参数 94 out.print(param); 95 // flush输出流的缓冲 96 out.flush(); 97 // 定义BufferedReader输入流来读取URL的响应 98 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 99 String line; 100 while ((line = in.readLine()) != null) { 101 result += line; 102 } 103 } catch (Exception e) { 104 System.out.println("发送 POST 请求出现异常!" + e); 105 e.printStackTrace(); 106 } 107 // 使用finally块来关闭输出流、输入流 108 finally { 109 try { 110 if (out != null) { 111 out.close(); 112 } 113 if (in != null) { 114 in.close(); 115 } 116 } catch (IOException ex) { 117 ex.printStackTrace(); 118 } 119 } 120 return result; 121 } 122 123 /** 124 * 获取key=value格式字符串 125 * 126 * @param map 127 * @return 128 */ 129 public static String getKeyVAlueSting(Map<String, String> map) { 130 String sign = ""; 131 132 Set<String> set = map.keySet(); 133 for (String key : set) { 134 sign += key + "=" + map.get(key) + "&"; 135 } 136 137 sign = sign.substring(0, sign.length() - 1); 138 139 return sign; 140 } 141 142 public static void main(String[] args) { 143 HttpRequest httpRequest = new HttpRequest(); 144 145 //测试微信项目中通过post请求获取access token 146 String url = "https://api.weixin.qq.com/cgi-bin/token"; 147 String param = "grant_type=client_credential&appid=wxfc27805daac56d9b&secret=12d853529003c68d0d2c9d4f87dd8b57"; 148 String sr=HttpRequest.sendPost(url, param); 149 System.out.println(sr); 150 } 151 }
Json格式、Post请求:
1 /**Map转json post请求*/ 2 public void a(){ 3 Map<String, String> map = new LinkedHashMap<>(); 4 map.put("type",type) 5 Map<String, String> requestMap = new LinkedHashMap<>(); 6 requestMap.put("bg_url", bg_url); 7 requestMap.put("biz_code", biz_code); 8 requestMap.put("sign", sign); 9 map.put("data",requestMap); 10 // 组装请求参数,JSON格式 11 JSONObject json = new JSONObject(map); 12 13 String result=sendPostJson("请求地址url",json.toJSONString()); 14 } 15 16 /** 17 * Post请求、 Json格式 18 * @param strURL 19 * @param params 20 * @return 21 */ 22 public static String sendPostJson(String strURL, String params) { 23 BufferedReader reader = null; 24 try { 25 URL url = new URL(strURL);// 创建连接 26 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 27 connection.setDoOutput(true); 28 connection.setDoInput(true); 29 connection.setUseCaches(false); 30 connection.setInstanceFollowRedirects(true); 31 connection.setRequestMethod("POST"); // 设置请求方式 32 connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 33 connection.connect(); 34 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码 35 out.append(params); 36 out.flush(); 37 out.close(); 38 // 读取响应 39 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 40 String line; 41 String res = ""; 42 while ((line = reader.readLine()) != null) { 43 res += line; 44 } 45 reader.close(); 46 return res; 47 } catch (IOException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } 51 return ""; // 自定义错误信息 52 }