java代码实现http请求

/**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String sendPost(String url, JSONObject param) throws Exception {
        StringBuilder builder = new StringBuilder();
        int count = 0;
        for(String key : param.keySet()){
            builder.append(key).append("=").append(param.get(key));
            count ++;
            if(count < param.size()){
                builder.append("&");
            }
        }
        return sendPost(url,builder.toString());
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String sendPost(String url, String param) throws Exception {
        HttpURLConnection conn =null;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.addRequestProperty("encoding", "UTF-8");//添加请求属性
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);// 是否输入参数
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(100000);// 连接超时单位毫秒 //
	    conn.setReadTimeout(200000);// 读取超时 单位毫秒
            //conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//Content-Type: application/x-www-form-urlencoded
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            System.out.println("参数="+param);
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            StringBuffer result = new StringBuffer();
			String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
             conn.disconnect();
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

public static String doGet(String url) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();
        try{
        URL httpUrl = new URL(url);
        conn = (HttpURLConnection)httpUrl.openConnection();
        conn.setRequestMethod("GET");
       // conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setConnectTimeout(100000);// 连接超时单位毫秒
        conn.setReadTimeout(200000);// 读取超时 单位毫秒
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.connect();
//        PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
//        out.print();

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line);
        }
        }catch (Exception e){

        }finally {
           try {
                reader.close();
              } catch (IOException e) {
                e.printStackTrace();
              }
              conn.disconnect();
          }
        }
        return sb.toString();
    }

posted @ 2021-12-21 15:14  张安东  阅读(267)  评论(0编辑  收藏  举报