java调用http接口

最近几天因为项目需求,做一个门禁管理。而门禁信息来源则是妙兜。所以我们这边需要调用妙兜的接口,主要是“设备安装登记接口”和“钥匙凭证发放接口”。

因为之前没有做过“java调用http接口”类似功能,所以在网上找了很多,也比较久。如下代码感觉比较可以,使用过程中也没出什么问题,所以就记录了下来。

    代码如下:

[java]  view plain  copy
  1. package com.zhang.miaodou;  
  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. public class DemoTest1 {  
  11.   
  12.     public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32";  
  13. //    public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list";  
  14.     // 妙兜测试接口  
  15.     public static final String POST_URL = "http://121.40.204.191:8180/mdserver/service/installLock";  
  16.       
  17.     /** 
  18.      * 接口调用 GET 
  19.      */  
  20.     public static void httpURLConectionGET() {  
  21.         try {  
  22.             URL url = new URL(GET_URL);    // 把字符串转换为URL请求地址  
  23.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接  
  24.             connection.connect();// 连接会话  
  25.             // 获取输入流  
  26.             BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));  
  27.             String line;  
  28.             StringBuilder sb = new StringBuilder();  
  29.             while ((line = br.readLine()) != null) {// 循环读取流  
  30.                 sb.append(line);  
  31.             }  
  32.             br.close();// 关闭流  
  33.             connection.disconnect();// 断开连接  
  34.             System.out.println(sb.toString());  
  35.         } catch (Exception e) {  
  36.             e.printStackTrace();  
  37.             System.out.println("失败!");  
  38.         }  
  39.     }  
  40.       
  41.     /** 
  42.      * 接口调用  POST 
  43.      */  
  44.     public static void httpURLConnectionPOST () {  
  45.         try {  
  46.             URL url = new URL(POST_URL);  
  47.               
  48.             // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
  49.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中  
  50.               
  51.             // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
  52.             connection.setDoOutput(true);  
  53.               
  54.             // 设置连接输入流为true  
  55.             connection.setDoInput(true);  
  56.               
  57.             // 设置请求方式为post  
  58.             connection.setRequestMethod("POST");  
  59.               
  60.             // post请求缓存设为false  
  61.             connection.setUseCaches(false);  
  62.               
  63.             // 设置该HttpURLConnection实例是否自动执行重定向  
  64.             connection.setInstanceFollowRedirects(true);  
  65.               
  66.             // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
  67.             // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
  68.             // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】  
  69.             connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded;charset=utf-8");     
  70.               
  71.             // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
  72.             connection.connect();  
  73.               
  74.             // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
  75.             DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
  76.               
  77.             String app_key = "app_key="+ URLEncoder.encode("4f7bf8c8260124e6e9c6bf094951a111""utf-8");        // 已修改【改为错误数据,以免信息泄露】  
  78.             String agt_num = "&agt_num="+ URLEncoder.encode("10111""utf-8");              // 已修改【改为错误数据,以免信息泄露】  
  79.             String pid = "&pid="+ URLEncoder.encode("BLZXA150401111""utf-8");             // 已修改【改为错误数据,以免信息泄露】  
  80.             String departid = "&departid="+ URLEncoder.encode("10007111""utf-8");         // 已修改【改为错误数据,以免信息泄露】  
  81.             String install_lock_name = "&install_lock_name="+ URLEncoder.encode("南天大门""utf-8");  
  82.             String install_address = "&install_address="+ URLEncoder.encode("北京育新""utf-8");  
  83.             String install_gps = "&install_gps="+ URLEncoder.encode("116.350888,40.011001""utf-8");  
  84.             String install_work = "&install_work="+ URLEncoder.encode("小李""utf-8");  
  85.             String install_telete = "&install_telete="+ URLEncoder.encode("13000000000""utf-8");  
  86.             String intall_comm = "&intall_comm="+ URLEncoder.encode("一切正常""utf-8");  
  87.               
  88.             // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444  
  89.             String parm = app_key+ agt_num+ pid+ departid+ install_lock_name+ install_address+ install_gps+ install_work+ install_telete+ intall_comm;  
  90.               
  91.             // 将参数输出到连接  
  92.             dataout.writeBytes(parm);  
  93.               
  94.             // 输出完成后刷新并关闭流  
  95.             dataout.flush();  
  96.             dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
  97.               
  98. //            System.out.println(connection.getResponseCode());  
  99.               
  100.             // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
  101.             BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
  102.             String line;  
  103.             StringBuilder sb = new StringBuilder(); // 用来存储响应数据  
  104.               
  105.             // 循环读取流,若不到结尾处  
  106.             while ((line = bf.readLine()) != null) {  
  107. //                sb.append(bf.readLine());  
  108.                 sb.append(line).append(System.getProperty("line.separator"));  
  109.             }  
  110.             bf.close();    // 重要且易忽略步骤 (关闭流,切记!)   
  111.             connection.disconnect(); // 销毁连接  
  112.             System.out.println(sb.toString());  
  113.       
  114.         } catch (Exception e) {  
  115.             e.printStackTrace();  
  116.         }  
  117.     }  
  118.       
  119.     public static void main(String[] args) {  
  120. //        httpURLConectionGET();  
  121.         httpURLConnectionPOST();  
  122.     }  
  123. }  


   只使用了POST请求方法 ,GET没有用,为了保证代码完整性所以没有删除GET请求代码 
     返回结果:

[java]  view plain  copy
  1. {  
  2.   "status" : "fail",  
  3.   "code" : "ERR001",  
  4.   "msg" : "商户10111不存在"  
  5. }  

猜你喜欢

转载自blog.csdn.net/qq_33223299/article/details/80338441