HttpClient 主方法里面

/*

Android studio如何添加HttClient

创建时间:2017/9/28 18:12
作者:874059604@qq.com
Android studio如何添加HttClient
  1. 在build.gradle文件中添加 useLibrary 'org.apache.http.legacy' ,如下图示:

添加完之后,点击右上角按钮,进行编译
  1. 使用HttpClient访问 https://请求的协议,需要添加以下代码,在创建HttpClient之前
    SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
*/ public class Fragment_two extends Fragment { private ListView one_Listview; private String Path= "http://www.meirixue.com/api.php?c=index&a=index"; private ListBaseadapter listBaseadapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View inflate = inflater.inflate(R.layout.fragment_two,container,false); initView(inflate); new asyncTask().execute(Path); return inflate; } class asyncTask extends AsyncTask<String,Void,String> { //子线程 @Override protected String doInBackground(String... params) { try { //1.创建一个HttpClient HttpClient hc=new DefaultHttpClient(); //2.创建HttpGet对象 HttpGet hg=new HttpGet(params[0]); //3.执行 HttpResponse response=hc.execute(hg); //4.判断返回码 int code=response.getStatusLine().getStatusCode(); if(code==200){ //5.得到结果 HttpEntity result=response.getEntity(); //转换成string类型 String s= EntityUtils.toString(result); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } //主线程 @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("SSS", "json:"+s); Gson gson = new Gson(); MyBean myBean = gson.fromJson(s, MyBean.class); List<MyBean.DataBean.IndexothersBean> list = myBean.getData().getIndexothers(); List_Baseadapter list_baseadapter = new List_Baseadapter(getActivity(), list); one_Listview.setAdapter(list_baseadapter); } } //解析 private String streamToString(InputStream inputStream, String s) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String a = ""; StringBuilder stringBuilder = new StringBuilder(); while ((a = bufferedReader.readLine()) != null) { stringBuilder.append(a); } bufferedReader.close(); return stringBuilder.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } //获得控件 private void initView(View inflate) { one_Listview = (ListView) inflate.findViewById(R.id.two_listview); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值