A simple example of HttpURLConnection and HttpClient in Android

  • 2020-05-17 06:32:01
  • OfStack

1: HttpHelper java


public class HttpHelper {
    //1: The standard Java interface 
    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 interface 
    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;
    }
}


Related articles: