java后台发送请求获取数据,并解析json数据

  先写一个发送请求的一个工具类BackEndHttpRequest

 

package com.bs.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class BackEndHttpRequest {
    /**
     * 向指定的URL发送GET方法的请求
     * @param url    发送请求的URL
     * @param param  请求参数,请求参数应该是 name1=value1&name2=value2 的形式 
     * @return       远程资源的响应结果 
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader bufferedReader = null;
        try {
            //1、读取初始URL
            String urlNameString = url + "?" + param;
            //2、将url转变为URL类对象
            URL realUrl = new URL(urlNameString);
            
            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            
            //5、建立实际的连接 
            connection.connect();
            //获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            //遍历所有的响应头字段
            for(String key : map.keySet()) {
                System.out.println(key + "---->" + map.get(key));
            }
            
            //6、定义BufferedReader输入流来读取URL的响应内容 ,UTF-8是后续自己加的设置编码格式,也可以去掉这个参数
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line = "";
            while(null != (line = bufferedReader.readLine())) {
                result += line;
            }
//            int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }
            
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("发送GET请求出现异常!!!"  + e);
            e.printStackTrace();
        }finally {        //使用finally块来关闭输入流 
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定的URL发送POST方法的请求
     * @param url    发送请求的URL
     * @param param  请求参数,请求参数应该是 name1=value1&name2=value2 的形式 
     * @return       远程资源的响应结果 
     */
    public static String sendPost(String url, String param) {
        String result = "";
        BufferedReader bufferedReader = null;
        PrintWriter out = null;
        try {
            //1、2、读取并将url转变为URL类对象
            URL realUrl = new URL(url);
            
            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        
            // 发送POST请求必须设置如下两行  
            connection.setDoInput(true);
            connection.setDoOutput(true);
            
            //5、建立实际的连接
            //connection.connect();
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            //发送请求参数
            out.print(param);
            //flush输出流的缓冲
            out.flush();
            //
            
            //6、定义BufferedReader输入流来读取URL的响应内容
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while(null != (line = bufferedReader.readLine())) {
                result += line;
            }
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("发送POST请求出现异常!!!"  + e);
            e.printStackTrace();
        }finally {        //使用finally块来关闭输出流、输入流 
            try {
                if(null != out) {
                    out.close();
                }
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }
}

 

测试:

 

package com.bs.utils;

import java.util.Timer;

public class Test {
    public static void main(String[] args) {
        
         //发送 GET 请求
        String str1=BackEndHttpRequest.sendGet("http://localhost:8080/showWaterregion", "page=1&rows=5&regionID=4");
        System.out.println(str1);
        
        //发送 POST 请求
        String str2=BackEndHttpRequest.sendPost("http://localhost:8080/waterregion/flow/year", "type=1&regionID=2");
     System.out.println(str2);
} }

 

postman请求数据

get请求的结果此处略;

post请求的结果:

 

 

 

进行解析请求回的json数据:

依赖jar包:

 fastjson-1.2.47.jar

   <dependency>
         <groupId>org.json</groupId>
         <artifactId>json</artifactId>
         <version>20160810</version>
     </dependency>

 

 

 测试:

 

package com.bs.utils;

import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String[] args) {
         //发送 GET 请求
        String str1=BackEndHttpRequest.sendGet("http://localhost:8080/showWaterregion", "page=1&rows=5&regionID=4");
        System.out.println(str1);
        
        //发送 POST 请求
        String str2=BackEndHttpRequest.sendPost("http://localhost:8080/waterregion/flow/year", "type=1&regionID=2");
        
        System.out.println("get请求json数据-----------------"+str1);
        
        JSONObject getjson = new JSONObject(str1);                //创建json对象(Json数据)
        System.out.println(getjson.get("total"));
        JSONArray getarray = getjson.getJSONArray("rows");        //获取json中的数组(数组名)
        for (int i = 0; i < getarray.length(); i++) {            //遍历数组
            JSONObject sonObject = getarray.getJSONObject(i);    //获得数组中的第一个对象
            System.out.println(sonObject.get("id"));            //根据字段名获得对象的每一个属性字段
            System.out.println(sonObject.get("name"));
            System.out.println(sonObject.get("readtime"));
        }
        
        
        System.out.println("post请求json数据-----------------"+str2);
        
        JSONObject json = new JSONObject(str2);
        System.out.println(json.get("status"));
        System.out.println(json.get("msg"));
        JSONArray jsonArray = json.getJSONArray("data");
        System.out.println(jsonArray);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject sonObject = jsonArray.getJSONObject(i);
            String s = (String) sonObject.get("time");
            Double bigDecimal = (Double) sonObject.get("flow");
            System.out.println(s);
            System.out.println(bigDecimal);
        }
    }
}

 

posted @ 2019-04-09 16:42  MoMing·  阅读(5027)  评论(0编辑  收藏  举报