使用java请求调用http

请求HTTP的代码:

向指定的url地址发送POST请求

 /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param charset
     *             发送和接收的格式
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Map<String, Object> param, String charset) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        String line;
        StringBuffer sb=new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 设置请求格式
            conn.setRequestProperty("contentType", charset);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间,这是一毫秒为单位的,建议调大一点,或者先不使用,否则请求超时容易报错
            conn.setConnectTimeout(60);
            conn.setReadTimeout(60);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),charset));
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            result=sb.toString();
        } catch (Exception e) {
            System.out.println("发送 POST请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

请求代码:

  public static void main(String args[]) {
        String postUrl = "http://192.168.4.10:80/api/json";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg_id","1036");
        map.put("lib_id",1);
        map.put("img_id", "a975b317-5e20-488b-a67f-050147983c09");
        //我这个http参数格式需要是json格式,所以需要先转换一下
        JSONObject jsonMap = JSONObject.fromObject(map);
        //打印转换的格式
        System.out.println("map转换json"+"  "+jsonMap);
        //输出请求返回的结果
        System.out.println("Post请求2:" + FaceDemo.sendPost(postUrl, jsonMap, "utf-8"));
    }

这是我使用post请求时一共导入的包其中有一些是Map集合转json]时所需要的详情请点击查看上篇文章

在这里插入图片描述
以上亲测可用
get方法类似。就没再测试,如果需要可以试试列举在下方了

  /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param charset         
     *             发送和接收的格式
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param,String charset) {
        String result = "";
        String line;
        StringBuffer sb=new StringBuffer();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 设置请求格式
            conn.setRequestProperty("contentType", charset); 
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(60);
            conn.setReadTimeout(60);
            // 建立实际的连接
            conn.connect();
            // 定义 BufferedReader输入流来读取URL的响应,设置接收格式
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),charset));
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            result=sb.toString();
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

请求代码:

  public static void main(String args[]) {
        String postUrl = "http://后边跟你需要请求的接口就好了";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name","1213");
        map.put("id",1);
        map.put("img_id", "a975b31");
        System.out.println("Get请求2:"+MyHttpRequest.sendGet(getUrl, map,"utf-8"));
    }

发布了81 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44411569/article/details/100048731