java 接口调用

生产中遇到过这种问题,记录下java的接口调用问题。

一种是json方式;

 public static String sendPost(String url, JSONObject obj)throws IOException{
                   OutputStreamWriter out = null;
                   BufferedReader reader = null;
                   String response="";
                   
/*                   String paramStr = "";
                if (null != param) { //遍历参数Map添加到集合中
                    Set<String> keySet = param.keySet();
                    for (String key : keySet) {
                        paramStr = paramStr + key + ":" + param.get(key) + "&";
                    }
                }
                int lastAndIndex = paramStr.lastIndexOf("&");
                if (lastAndIndex != -1) {
                    paramStr = paramStr.substring(0, lastAndIndex);
                }
                
                System.out.println("地址===" + url);
                System.out.println("入参===" + paramStr);*/
                
                   try {
                       URL httpUrl = null; //HTTP URL类 用这个类来创建连接
                       //创建URL
                       httpUrl = new URL(url);
                       //建立连接
                       HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                       conn.setRequestProperty("accept", "*/*");// 设置通用的请求属性
                       conn.setRequestProperty("Charset", "UTF-8");
                       conn.setRequestMethod("POST");
                       conn.setRequestProperty("Content-Type", "application/json");
                       conn.setRequestProperty("connection", "keep-alive");
                       conn.setUseCaches(false);//设置不要缓存
                       conn.setInstanceFollowRedirects(true);
                       conn.setDoOutput(true);
                       conn.setDoInput(true);
                       conn.connect();
                       //POST请求
                       out = new OutputStreamWriter(
                               conn.getOutputStream());
                       out.write(obj.toJSONString());
                       out.flush();
                       //读取响应
                       reader = new BufferedReader(new InputStreamReader(
                               conn.getInputStream()));
                       String lines;
                       while ((lines = reader.readLine()) != null) {
                           lines = new String(lines.getBytes(), "utf-8");
                           response+=lines;
                       }
                       reader.close();
                       // 断开连接
                       conn.disconnect();
                   } catch (Exception e) {
                   System.out.println("发送 POST 请求出现异常!"+e);
                   e.printStackTrace();
                   }
                   //使用finally块来关闭输出流、输入流
                   finally{
                   try{
                       if(out!=null){
                           out.close();
                       }
                       if(reader!=null){
                           reader.close();
                       }
                   }
                   catch(IOException ex){
                       ex.printStackTrace();
                   }
               }
           
                   return response;
               }

再来一个普通的str 调用接口;

    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostWebReq(String url, Map<String, Object> param,int i) throws Exception {
        String paramStr = "";
        if (null != param) { //遍历参数Map添加到集合中
            Set<String> keySet = param.keySet();
            for (String key : keySet) {
                paramStr = paramStr + key + "=" + param.get(key) + "&";
            }
        }
        int lastAndIndex = paramStr.lastIndexOf("&");
        if (lastAndIndex != -1) {
            paramStr = paramStr.substring(0, lastAndIndex);
        }
        
        System.out.println("地址===" + url);
        System.out.println("入参===" + paramStr);
        
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();// 打开和URL之间的连接
            conn.setRequestProperty("accept", "*/*");// 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setDoOutput(true);// 发送POST请求必须设置如下两行
            conn.setDoInput(true);// 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));// 发送请求参数
            out.print(paramStr);// flush输出流的缓冲
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));// 定义BufferedReader输入流来读取URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            throw e;
        } finally { // 使用finally块来关闭输出流、输入流
            try {
                if (in != null) in.close();
            } catch (IOException ex) { }
            if (out != null) out.close();
        }
        return result;
    }

 

posted on 2018-05-08 11:27  手撕高达的村长  阅读(306)  评论(0编辑  收藏  举报

导航