欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

post请求网络数据

程序员文章站 2024-01-27 08:45:04
...
 //post请求
    public static String httpPost(String str1, String str2) {
//        http://apis.juhe.cn/cook/query   ?    key=&menu=蛋炒饭
        try {
            //设置url
            URL url = new URL(str1);
            //获取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置为post请求
            connection.setRequestMethod("POST");
            //使用写入和读取(post请求必须要写这个俩)
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //
            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.write(str2);// key=  &menu=蛋炒饭
            writer.flush();
            ;//刷新
            //判断是否成功
            int code = connection.getResponseCode();
            if (code == 200) {
                //读取数据
                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
                //拼接字符串
                StringBuilder builder = new StringBuilder();
                String s = "";
                //读取数据
                while ((s = reader.readLine()) != null) {
                    //拼接字符串
                    builder.append(s);
                }

                return builder.toString();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }在这里插入代码片
相关标签: post请求网络数据