HttpURLConnection和HttpClient的AsyncTask

//用到的权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
//用到的依赖

useLibrary 'org.apache.http.legacy'

 

implementation 'com.google.guava:guava:16.0.1'
implementation 'com.google.code.gson:gson:2.2.4'
//mainactivity

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private RadioGroup group;
    private List<Fragment> fList;
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewP);
        group = findViewById(R.id.group);
        fList = new ArrayList<>();

        fList.add(new FragmentOne());
        fList.add(new FragmentTwo());

        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fList.get(position);

            }

            @Override
            public int getCount() {
                return fList.size();
            }
        });
//        小圆点
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        group.check(R.id.but1);
                        break;
                    case 1:
                        group.check(R.id.but2);
                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.but1:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.but2:
                        viewPager.setCurrentItem(1);
                        break;
                    default:
                        break;
                }
            }
        });

    }
}

//fragmentOne

public class FragmentOne extends Fragment {
    public static final String TAG = FragmentOne.class.getSimpleName();
    private View view;
    private ListView lv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//解决与系统view的冲突
        if(view == null){
            view = inflater.inflate(R.layout.one,container,false);
        }
        ViewGroup parent = (ViewGroup)view.getParent();
        if(parent != null){
            parent.removeView(view);
        }

        //资源ID的获取
        lv = view.findViewById(R.id.lv);

        //当点击子条目时,跳转到webActivity
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean.DataBean.ToutiaoBean newsBean = (NewsBean.DataBean.ToutiaoBean) parent.getAdapter().getItem(position);
                //进行跳转
                Intent intent = new Intent(getActivity(), WebActivity.class);
                //将数据传入web并且展示
                intent.putExtra("url",newsBean.getLink());
                //启动跳转
                startActivity(intent);

            }
        });

        new HttpURLConnectionGetDataTask().execute("https://www.apiopen.top/journalismApi");//地址

        return view;
    }
//使用 HttpURLConnectionGetDataTask 的 AsyncTask 做
    class HttpURLConnectionGetDataTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... strings) {

            try {
                URL url = new URL(strings[0]);//地址的调用
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");//读取的方式
                urlConnection.setConnectTimeout(3000);//响应时间
                urlConnection.setReadTimeout(3000);//读取时间

                //判断状态码
                if (urlConnection.getResponseCode() == 200){
                    return CharStreams.toString(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

                }

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

        @Override
        protected void onPostExecute(String s) {
            Log.i(TAG,"ssssssss" + s);
            Gson gson = new Gson();//解析
            NewsBean newsBean = gson.fromJson(s, NewsBean.class);

            lv.setAdapter(new UrlAdapter(getActivity(), newsBean.getData().getToutiao()));
        }
    }


}

//fragmetTwo使用的是httpclient

public class FragmentTwo extends Fragment {
    public static final String TAG = FragmentOne.class.getSimpleName();
    private View view;
    private ListView listIew;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(view == null){
            view = inflater.inflate(R.layout.two,container,false);
        }
        ViewGroup parent = (ViewGroup)view.getParent();
        if(parent != null){
            parent.removeView(view);
        }

        listIew  = view.findViewById(R.id.lvs);
        listIew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean.DataBean.ToutiaoBean newsBean = (NewsBean.DataBean.ToutiaoBean) parent.getAdapter().getItem(position);

                Intent intent = new Intent(getActivity(), WebActivity.class);

                intent.putExtra("url",newsBean.getLink());
                Toast.makeText(getActivity(),"ssssssss",Toast.LENGTH_SHORT).show();
                startActivity(intent);
            }
        });

        new HttpClientGetDataTask().execute("https://www.apiopen.top/journalismApi");
        return view;
    }
//使用AsyncTask
    private class HttpClientGetDataTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(strings[0]);

            try {
                HttpResponse response = client.execute(get);
                //判断状态码
                if (response.getStatusLine().getStatusCode() == 200){
                    return EntityUtils.toString(response.getEntity());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            Gson gson = new Gson();//解析
            NewsBean newsBean = gson.fromJson(s,NewsBean.class);
            listIew.setAdapter(new UrlAdapter(getActivity(),newsBean.getData().getToutiao()));
        }
    }
}

//WebActivity

public class WebActivity extends AppCompatActivity {

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        webView = findViewById(R.id.webview);//获取资源ID

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }


            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
            }
        });
        webView.loadUrl(getIntent().getStringExtra("url"));//得到地址里面的链接
    }
}

//Adapter

public class UrlAdapter extends BaseAdapter {

    private Context context;
    private List<NewsBean.DataBean.ToutiaoBean> list;

    public UrlAdapter(Context context, List<NewsBean.DataBean.ToutiaoBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null){
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.url_item,null);

            holder.textView = convertView.findViewById(R.id.text_1);
            holder.textView2 = convertView.findViewById(R.id.text_2);

            convertView.setTag(holder);

        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(list.get(position).getTitle());
        holder.textView2.setText(list.get(position).getType());

        return convertView;
    }

    class ViewHolder{
        TextView textView,textView2;
    }
}

//main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bwie.wangbingjun.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewP"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="9"
        >
    </android.support.v4.view.ViewPager>


    <RadioGroup
        android:id="@+id/group"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        >

        <RadioButton
            android:id="@+id/but1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:button="@null"
            android:checked="true"
            android:padding="8dp"
            android:text="HttpURLConnection"
            />
        <RadioButton
            android:id="@+id/but2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:button="@null"
            android:padding="8dp"
            android:text="HttpClient"
            />

    </RadioGroup>

</LinearLayout>

//web.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bwie.wangbingjun.WebActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</android.support.constraint.ConstraintLayout>

//one

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#cee"
    >

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>
</LinearLayout>

 

//two

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    >

    <ListView
        android:id="@+id/lvs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>
</LinearLayout>

 

//item

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/text_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginTop="33dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/text_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@id/text_1"
        android:layout_alignRight="@id/text_1"
        android:layout_below="@id/text_1"
        android:layout_marginTop="40dp"
        android:text="TextView" />
</RelativeLayout>

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个关于Android应用开发的问题。首先,我可以给您提供一个示例代码,它演示了如何使用HttpClient获取百度地图,并将其显示在ImageView中。但需要注意的是,由于Android 9以及更高版本禁止使用HttpClient,因此推荐使用OkHttpHttpURLConnection。以下是示例代码: ``` public class MainActivity extends AppCompatActivity { private EditText etLocation; private EditText etZoom; private Button btnShowMap; private ImageView ivMap; private String location; private int zoom; private static final String BAIDU_MAP_URL = "https://api.map.baidu.com/staticimage"; private static final String BAIDU_MAP_KEY = "您的百度地图API Key"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etLocation = findViewById(R.id.et_location); etZoom = findViewById(R.id.et_zoom); btnShowMap = findViewById(R.id.btn_show_map); ivMap = findViewById(R.id.iv_map); btnShowMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { location = etLocation.getText().toString(); zoom = Integer.parseInt(etZoom.getText().toString()); new GetMapTask().execute(); } }); } private class GetMapTask extends AsyncTask<Void, Void, Bitmap> { @Override protected Bitmap doInBackground(Void... voids) { Bitmap bitmap = null; try { HttpClient httpClient = new DefaultHttpClient(); String url = BAIDU_MAP_URL + "?width=" + ivMap.getWidth() + "&height=" + ivMap.getHeight() + "&center=" + URLEncoder.encode(location, "UTF-8") + "&zoom=" + zoom + "&ak=" + BAIDU_MAP_KEY; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); InputStream inputStream = httpEntity.getContent(); bitmap = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { if (bitmap != null) { ivMap.setImageBitmap(bitmap); } } } } ``` 上述代码中,我们使用了HttpClient获取百度地图的静态图片,并在获取成功后将其显示在ImageView中。需要注意的是,我们需要在AndroidManifest.xml文件中添加以下权限: ``` <uses-permission android:name="android.permission.INTERNET" /> ``` 同时,需要在build.gradle文件中添加以下依赖项: ``` implementation 'org.apache.httpcomponents:httpclient:4.5.3' ``` 最后,需要替换BAIDU_MAP_KEY为您自己的百度地图API Key。如果您还没有API Key,可以在百度开放平台申请。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值