java网络请求GET和POST方式

GET方式

public static String readContentFromGet(String get_url) throws IOException { 


        String getURL = get_url;

        URL getUrl = new URL(getURL); 

        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 

        connection.connect(); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

        String lines; 
        
        StringBuffer strbuff = new StringBuffer();
        
        while ((lines = reader.readLine()) != null) { 
                
            strbuff.append(lines);
            System.out.println(lines); 

        } 

        reader.close(); 

        connection.disconnect(); 

        return strbuff.toString();

    } 

POST方式

public static String readContentFromPost(String str) throws IOException {
        // Post请求的url,与get不同的是不需要带参数
        URL postUrl = new URL(str);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        // 设置是否向connection输出,因为这个是post请求,参数要放在
        // http正文内,因此需要设为true
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        // Post 请求不能使用缓存
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
        // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
        // 进行编码
        connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); 
        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
        // 要注意的是connection.getOutputStream会隐含的进行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // The URL-encoded contend
        // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
        StringBuffer content = new StringBuffer();
        
        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
        out.writeBytes(content.toString()); 

        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        StringBuffer strbuff = new StringBuffer();
        
        while ((line = reader.readLine()) != null) {
            strbuff.append(line);
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();
        return strbuff.toString();
    }


发布了38 篇原创文章 · 获赞 17 · 访问量 17万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章