/*
Android studio如何添加HttClient
Android studio如何添加HttClient
- 在build.gradle文件中添加 useLibrary 'org.apache.http.legacy' ,如下图示:

添加完之后,点击右上角按钮,进行编译
-
使用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);
}
}