在安卓中我们使用HttpURLConnection来进行请求
我们看主activity的代码:public class TestHttpActivity extends Activity implements AdapterView.OnItemClickListener {
public static final String TAG = TestHttpActivity.class.getSimpleName();
private ArrayList mBookArrayList;
private BookMainAdapter mBookMainAdapter;
public static void startActivity(Context context) {
Intent intent = new Intent();
intent.setClass(context,TestHttpActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feeds_main);
initTitle();
ListView listView = (ListView) findViewById(R.id.news_home_listview);
mBookMainAdapter = new BookMainAdapter(this);
listView.setAdapter(mBookMainAdapter);
listView.setOnItemClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
new InitDataAsyncTask().execute();
}
private void initTitle() {
TitleBarCommon titleBarCommon = (TitleBarCommon)findViewById(R.id.head_common_layout);
titleBarCommon.setRightTextViewString("增加");
titleBarCommon.setRightTextViewListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BookDetail.startActivity(TestHttpActivity.this,null);
}
});
}
private class InitDataAsyncTask extends AsyncTask {
@Override
protected Void doInBackground(Void... params) {
HttpUtil httpUtil = new HttpUtil();
String url = "http://139.199.89.89/api/v1/books";
String response = httpUtil.get(TestHttpActivity.this,url);
Log.d(TAG,"response="+response);
parseResponse(response);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d(TAG,"<<<<
mBookMainAdapter.setList(mBookArrayList);
}
}
private void parseResponse(String response) {
try{
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray(response);
ArrayList books;
mBookArrayList = new Gson().fromJson(response, new TypeToken>(){}.getType());
}catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Book book = mBookArrayList.get(position);
BookDetail.startActivity(TestHttpActivity.this,book);
}
}
注意所有的网络请求都要放到子线程中,不然会报错
xml:<?xml version="1.0" encoding="utf-8"?>
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white_a"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
android:id="@+id/head_common_layout"
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="@color/red_bn"
android:gravity="center_vertical"/>
android:id="@+id/news_home_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:fadingEdge="none"
android:footerDividersEnabled="true"
android:listSelector="@color/trans_color"
android:scrollbars="none"
android:scrollingCache="false" />
看Get操作:public String get(Context context, final String strUrl) {
URL getUrl = null;
try {
getUrl = new URL(strUrl);
} catch (MalformedURLException ex) {
Log.e("HttpUtil", "get MalformedURL", ex);
return null;
}
InputStream input = null;
ByteArrayOutputStream byteOutStream = null;
HttpURLConnection conn = null;
byte[] outData = null;
try {
conn = getConnection(context, getUrl);
connection = conn;
conn.setConnectTimeout(TIMEOUT);
conn.setReadTimeout(TIMEOUT);
conn.setDoInput(true);
conn.connect();
input = conn.getInputStream();
String webcontent = null;
byteOutStream = new ByteArrayOutputStream();
//byte[] buf = new byte[BUF_LEN];
int i = 0;
while((i = input.read(tmpBuf)) != -1){
byteOutStream.write(tmpBuf, 0, i);
}
outData = byteOutStream.toByteArray();
if(outData != null && outData.length > 0){
webcontent = new String(outData);
}
return webcontent;
} catch (Exception ex) {
Log.e("HttpUtil", "get", ex);
//return ex.getMessage();
} finally {
try{
outData = null;
if(input != null){
input.close();
input = null;
}
if(byteOutStream != null){
byteOutStream.close();
byteOutStream = null;
}
if(conn != null){
conn.disconnect();
conn = null;
}
} catch(Exception ex){
Log.e("HttpUtil", "get finally", ex);
//return ex.getMessage();
}
}
return null;
}