zoukankan      html  css  js  c++  java
  • Java发送HTTP的Get 和 Post请求

    Java发送HTTP的Get 和 Post请求

    PostUtil 请求类

    package com.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.net.URLConnection;
    
    import net.sf.json.JSONObject;
    
    public class PostUtil {
        
        /**
         * 向指定 URL 发送POST方法的请求
         * @param url  发送请求的 URL
         * @param param  请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return  响应结果
         */
        public static JSONObject sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            JSONObject jsonObject = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
                out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 获取请求返回数据(设置返回数据编码为UTF-8)
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                jsonObject = JSONObject.fromObject(result);
                System.out.println(jsonObject);
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
    
            return jsonObject;
        }
    
    
    }

    调用测试

        public static void main(String[] args) throws IOException {
            //发送 POST 请求
            JSONObject sr=PostUtil.sendPost("http://localhost:8080/student", "id=2");
            System.out.println(sr);
        }

  • 相关阅读:
    2020.12.7
    IDEA修改代码后不用重新启动项目即可刷新
    期中测试人口普查登记题目
    Android去掉标题头
    Android限制输入框内容
    Android:setOnItemClickListener cannot be used with a spinner报错
    Android修改app图标
    将外部sqlite3数据库导入到Android项目中
    IDEA个人常用快捷键
    css选择器
  • 原文地址:https://www.cnblogs.com/dafei4/p/13111561.html
Copyright © 2011-2022 走看看