HttpURLConnection 当作请求调用接口不带返回参数的工具类

Posted remember-forget

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection 当作请求调用接口不带返回参数的工具类相关的知识,希望对你有一定的参考价值。

package cn.smartercampus.core.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpCilent {
    public String httpRequest(String req_url) {
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(req_url);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  

            httpUrlConn.setDoOutput(false);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  

            httpUrlConn.setRequestMethod("GET");  
            httpUrlConn.connect();  

            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

        } catch (Exception e) {  
            System.out.println(e.getStackTrace());  
        }  
        return buffer.toString();  
    }  
}

 

以上是关于HttpURLConnection 当作请求调用接口不带返回参数的工具类的主要内容,如果未能解决你的问题,请参考以下文章

转Java模拟http请求,调用外部api接口:HttpURLConnection和HttpClient的区别

HttpURLConnection发送请求

如何使用 HttpURLConnection 在请求正文中发送数据?

如何从 HttpURLConnection 实例获取 HTTP 请求字符串

HttpURLConnection请求

Android HttpUrlConnection如何在请求头中设置cookie?