码迷,mamicode.com
首页 > 其他好文 > 详细

请求网络

时间:2016-06-14 08:54:54      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

public class NetWorkUtils {
    public static String getString(String path){
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(path);
        
        try {
            HttpResponse response = client.execute(get);
            if(response.getStatusLine().getStatusCode()==200){
                String string = EntityUtils.toString(response.getEntity(), "utf-8");
                return string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }    return null;
    }
public class NetWorkUtils {
    public static String getString(String path){
        try {
            URL url =new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5*1000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if(code==200){
                InputStream inStream = conn.getInputStream();
                int len=-1;
                byte[] arr = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while((len=inStream.read(arr))!=-1){
                    builder.append(new String(arr,0,len));
                }
                return builder.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

请求网络

标签:

原文地址:http://www.cnblogs.com/gaoliangjie/p/5582698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!