请求网络工具类


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class HttpUtils {
    String result  = "";
    public static String getFromStringHttp(String urlstring){
        String result ="";
        try {
            URL url = new URL(urlstring);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setConnectTimeout(3000);
            connection.connect();

            int code = connection.getResponseCode();
            if (code ==200){
                InputStream is = connection.getInputStream();
                result = getInputStream(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
return result;
    }

    private static String getInputStream(InputStream is) {
        String result = "";

        int len = -1;
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            while ((len = is.read(buffer,0,buffer.length))!=-1){
                baos.write(buffer,0,len);
                baos.flush();
            }
            result = baos.toString();
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
return result;
    }
}

猜你喜欢

转载自blog.csdn.net/cxx13700/article/details/82824224