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);
        }

  • 相关阅读:
    HashMap 使用小结
    linux下的文本处理命令sed&awk&grep
    HashMap和Hashtable的区别 .Properties
    Linux awk简简单单
    linux配置java环境变量(详细)
    linux后台运行程序及恢复
    为什么需要 单例设计模式(Singleton)?
    Linux文本处理命令
    使用Perf4J进行性能分析和监控
    sqlldr的用法总结
  • 原文地址:https://www.cnblogs.com/dafei4/p/13111561.html
Copyright © 2011-2022 走看看