java代码分别发送get和post请求。

    /**
     * 发送get请求
     */
    public static String sendGet(String url,String param){
        String result="";
        try {
            url += "?"+param;
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            connection.setRequestProperty("accept", "text/html");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
            connection.connect();
            
            Map<String, List<String>> map = connection.getHeaderFields();
            for(String key:map.keySet()){
                System.out.println(key+"---"+map.get(key));
            }
            
            // 定义输入流来读取URL的内容
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while((line = bufferedReader.readLine())!=null){
                result += "\r\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 发送post请求
     */
    public static String sendPost(String url,String param){
        String result="";
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
            printWriter.print(param);
            printWriter.flush();
            
            // 定义输入流来读取URL的内容
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while((line = bufferedReader.readLine())!=null){
                result += "\r\n" + line;
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


猜你喜欢

转载自blog.csdn.net/leadseczgw01/article/details/79123657