您的位置:首页 > 理论基础 > 计算机网络

Android 中HttpURLConnection与HttpClient使用的简单实例

2013-10-15 16:52 1016 查看

1:HttpHelper.java

复制代码 代码如下:
public class HttpHelper {
    //1:标准的Java接口
    public static String getStringFromNet1(String param){
        String result="";
        try{
            URL url=new URL(param);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                InputStream is=conn.getInputStream();
                byte[]data=new byte[1024];
                int len=is.read(data);
                result=new String(data,0,len);
                is.close();
                conn.disconnect();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

    //2:Apache接口
    public static String getStringFromNet2(String param){
        String result="";
        try{
            HttpClient client=new DefaultHttpClient();
            HttpGet get=new HttpGet(param);
            HttpResponse response=client.execute(get);
            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                result=EntityUtils.toString(response.getEntity());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息