HttpURLConnection 和 HttpClient

//请求json方法

public static String getJson(String urlString) {
    try {
   
	//封装url接口
        URL url = new URL(urlString);
        //打开了连接
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        
        int responseCode = urlConnection.getResponseCode();
        
        if (responseCode == 200) {
            InputStream inputStream = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String t="";
            StringBuilder stringBuilder = new StringBuilder();
            while ((t  =bufferedReader.readLine()) != null){
                stringBuilder.append(t);
            }
            return  stringBuilder.toString();
        } else {
            
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

//请求网络图片方法

public static Bitmap getBitmpa(String mUrl) {
    try {
		//封装url接口
        URL url = new URL(mUrl);
        //打开了连接
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        int responseCode = urlConnection.getResponseCode();
		if (responseCode == 200) {
            InputStream inputStream = urlConnection.getInputStream();
			//得到图片
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        } else {
           
        }
		
		
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

HttpClient

  1. .grade里
    android{
    下面 useLibrary ‘org.apache.http.legacy’

  2. Activity里 继承AppCompatActivity
    开线程

            try {
    
                //发送请求的对象
                DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
                //请求方式
                HttpGet httpGet = new HttpGet(urlString);
                //发送请求
                HttpResponse response = defaultHttpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    String jsonResult = EntityUtils.toString(entity);
                    Log.e("可以自己名","statusCode--请求成功json--->:"+jsonResult);
                }else {
                    Log.e("可以自己名","statusCode--请求失败:"+statusCode);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    

猜你喜欢

转载自blog.csdn.net/weixin_43805224/article/details/84726675