SoFunction
Updated on 2025-03-01

Simple examples of using HttpURLConnection and HttpClient in Android


public class HttpHelper {
//1: Standard Java interface
    public static String getStringFromNet1(String param){
        String result="";
        try{
            URL url=new URL(param);
            HttpURLConnection conn=(HttpURLConnection)();
            if(()==HttpURLConnection.HTTP_OK){
                InputStream is=();
                byte[]data=new byte[1024];
                int len=(data);
                result=new String(data,0,len);
                ();
                ();
            }
        }catch(Exception e){
            ();
        }
        return result;
    }

//2:Apache interface
    public static String getStringFromNet2(String param){
        String result="";
        try{
            HttpClient client=new DefaultHttpClient();
            HttpGet get=new HttpGet(param);
            HttpResponse response=(get);
            if(().getStatusCode()==HttpStatus.SC_OK){
                result=(());
            }
        }catch(Exception e){
            ();
        }
        return result;
    }
}