HttpURLConnection请求获取数据。

public class UrlConnect {
    public static void main(String[] args) throws Exception {
        String s = UrlConnect.urlConnectXml("http://localhost:8080/user/list", "{\"id\":\"1\"}");
        System.out.println(s);
    }

    public static String urlConnectXml(String urlStr,String jsonString) throws Exception {

        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        //请求头
        //设置传送的内容类型是可序列化的java对象
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        //设置请求方式,默认是Get
        urlConnection.setRequestMethod("POST");
        //请求不能使用缓存
        urlConnection.setUseCaches(false);
        //允许向urlConnection写出
        urlConnection.setDoOutput(true);
        //允许从urlConnection读入
        urlConnection.setDoInput(true);
        //获取连接
        urlConnection.connect();
        //得到输出流对象
        OutputStream outputStream = urlConnection.getOutputStream();
        DataOutputStream dataOutPutStream = new DataOutputStream(outputStream);
        //向输出流写数据,这些数据将存到内存缓冲区
        dataOutPutStream.write(jsonString.getBytes("utf-8"));
        //刷新对象输出流,将字节都写入到流中
        dataOutPutStream.flush();
        //调用getInputStream()函数时才把准备好的http请求正式发送到服务器,getInputStream的返回值是InputStream
        InputStream inputStream = urlConnection.getInputStream();
        //返回的输入流用于读取服务器对此次http请求返回的信息
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
        String s = "";
        StringBuilder stringBuilder = new StringBuilder();
        while((s = bufferedReader.readLine()) != null){
            stringBuilder.append(s);
        }
        bufferedReader.close();
        dataOutPutStream.close();
        return stringBuilder.toString();
    }
}

接口代码


@RestController
@RequestMapping("/user")
public class UserController {
    @ResponseBody
    @RequestMapping(value = "/lsit", method = RequestMethod.POST)
    public List<User> test123(@RequestBody JSONObject jsonObject) 
        return this.userService.getById(Integer.parseInt(id));

    }
}
在本地写了个接口并开启,写了个HttpURLConnection向这个接口发送请求获取数据,正好也复习一下字节流、转换流、缓存流的用法。记此笔记,方便查看!
	这个接口涉及到访问了数据库,需要在建个数据库接口,再写个实现类。如果做实验为了更方便,也可以不去访问数据库,直接return一个字符转也可以。

你可能感兴趣的:(常用知识记录)