java后台调用HttpURLConnection类模拟浏览器请求(一般用于接口调用)
项目开发中难免遇到外部接口的调用,小生今天初次接触该类,跟着API方法走了一遍,如有不对的地方,还请哆哆指正,拜谢!
1 package com.cplatform.movie.back.test; 2 3 import java.io.BufferedReader; 4 import java.io.DataOutputStream; 5 import java.io.InputStreamReader; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 import java.net.URLEncoder; 9 10 11 12 public class HttpURLConnectionTest { 13 public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32"; 14 public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list"; 15 16 /** 17 * 接口调用 GET 18 */ 19 public static void httpURLConectionGET() { 20 try { 21 URL url = new URL(GET_URL); // 把字符串转换为URL请求地址 22 HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接 23 connection.connect();// 连接会话 24 // 获取输入流 25 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 26 String line; 27 StringBuilder sb = new StringBuilder(); 28 while ((line = br.readLine()) != null) {// 循环读取流 29 sb.append(line); 30 } 31 br.close();// 关闭流 32 connection.disconnect();// 断开连接 33 System.out.println(sb.toString()); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 System.out.println("失败!"); 37 } 38 } 39 40 /** 41 * 接口调用 POST 42 */ 43 public static void httpURLConnectionPOST () { 44 try { 45 URL url = new URL(POST_URL); 46 47 // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
// 此时cnnection只是为一个连接对象,待连接中 48 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 49 50 // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数) 51 connection.setDoOutput(true); 52 53 // 设置连接输入流为true 54 connection.setDoInput(true); 55 56 // 设置请求方式为post 57 connection.setRequestMethod("POST"); 58 59 // post请求缓存设为false 60 connection.setUseCaches(false); 61 62 // 设置该HttpURLConnection实例是否自动执行重定向 63 connection.setInstanceFollowRedirects(true); 64 65 // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数) 66 // application/x-javascript text/xml->xml数据
// application/x-javascript->json对象
// application/x-www-form-urlencoded->表单数据 67 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 68 69 // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行) 70 connection.connect(); 71 72 // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容) 73 DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
//URLEncoder.encode()方法 为字符串进行编码(具体编码格式依据项目文档而定) 74 String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); 75 76 // 将参数输出到连接 77 dataout.writeBytes(parm); 78 79 // 输出完成后刷新并关闭流 80 dataout.flush(); 81 dataout.close(); // 重要且易忽略步骤 (关闭流,切记!) 82 83 System.out.println(connection.getResponseCode()); 84 85 // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader) 86 BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream())); 87 String line; 88 StringBuilder sb = new StringBuilder(); // 用来存储响应数据 89 90 // 循环读取流,若不到结尾处 91 while ((line = bf.readLine()) != null) { 92 sb.append(bf.readLine()); 93 } 94 bf.close(); // 重要且易忽略步骤 (关闭流,切记!) 95 connection.disconnect(); // 销毁连接 96 System.out.println(sb.toString()); 97 98 } catch (Exception e) { 99 e.printStackTrace(); 100 } 101 } 102 103 104 public static void main(String[] args) { 105 // httpURLConectionGET(); 106 httpURLConnectionPOST(); 107 } 108 }
a_day