====================utils下的NetWorkUtils==================
package com.example.utils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class NetWorkUtils {
static String tag = "TAG";
public static String getStr(String htt) {
String path = htt + "18938f9a9808b846aff0801f51d6efde";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
try {
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code ==200) {
String result = EntityUtils.toString(response.getEntity());
/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = response.getEntity().getContent();
byte[] arr = new byte[1024];
int len = 0;
while ((len = is.read(arr))!=-1) {
baos.write(arr, 0, len,"utf-8");
}*/
return result;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
=====================在mainActivity中调用======================
String htt = "http://japi.juhe.cn/comic/book?key=";
/*
* 解析
*/
private void initData() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
return NetWorkUtils.getStr(htt);
}
/**
*相当于子线程
/
@Override
protected void onPostExecute(String result) {
Gson gson = new Gson();
Type type = new TypeToken<BookList>() {
}.getType();
blist = gson.fromJson(result, type);
bl = blist.result.bookList;
// Log.e("TAG", bl.toString());
// 添加适配器,
lv.setAdapter(new MyBaseAdapter(getActivity(),bl));
}
}.execute();
}