package net.bwie.network.activity; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import net.bwie.network.R; import net.bwie.network.bean.KaiYan; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; /** * 下一页post请求 * 使用异步任务下载网络数据 * 使用gson解析 * 注:有时间看看我讲的原生json解析 */ public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String KAI_YAN_URL = "http://baobab.kaiyanapp.com/api/v4/tabs/selected?udid=11111&vc=168&vn=3.3.1&deviceModel=Huawei%36&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market&system_version_code=20"; protected Button mGetNetworkDataBtn; protected Button mGetPicBtn; protected ImageView mImageView; protected Button mNextBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); initView(); } @Override public void onClick(View view) { if (view.getId() == R.id.get_network_data_btn) { getDatas(); } else if (view.getId() == R.id.get_pic_btn) { getPicture(); } else if (view.getId() == R.id.next_btn) { PostActivity.startActivity(this); } } private void getDatas() { MyTask task = new MyTask(); task.execute(KAI_YAN_URL); } private void getPicture() { String imgUrl = "http://img.kaiyanapp.com/1699f3946ccd281230a1d887d169439f.png?imageMogr2/quality/60/format/jpg"; Picasso .with(this) .load(imgUrl) .into(mImageView); } private void initView() { mGetNetworkDataBtn = (Button) findViewById(R.id.get_network_data_btn); mGetNetworkDataBtn.setOnClickListener(MainActivity.this); mGetPicBtn = (Button) findViewById(R.id.get_pic_btn); mGetPicBtn.setOnClickListener(MainActivity.this); mImageView = (ImageView) findViewById(R.id.image_view); mNextBtn = (Button) findViewById(R.id.next_btn); mNextBtn.setOnClickListener(MainActivity.this); } private class MyTask extends AsyncTask<String, Void, List<KaiYan.ItemBean>> { @Override protected List<KaiYan.ItemBean> doInBackground(String... params) { String requestUrl = params[0]; // 使用HTTPUrlConnection try { URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 配置connection connection.setRequestMethod("GET");// GET或POST必须大写 // 连接网络 connection.connect(); // 判断是否连接成功 if (connection.getResponseCode() == 200) { // 获取来自网络的输入流 // 使用缓冲字符输入流 // 字节流转字符流 BufferedReader br = null; br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // 最终接收的json字符串 String json = ""; // 使用缓冲流读取到的每一行数据 String line = ""; while ((line = br.readLine()) != null) { json += line.trim(); } // json数据产生完毕,该解析了 Gson gson = new Gson(); KaiYan kaiYan = gson.fromJson(json, KaiYan.class); List<KaiYan.ItemBean> itemList = kaiYan.getItemList(); return itemList; } } catch (Exception e) { e.printStackTrace(); Log.d("1507", e.getMessage()); } return null; } @Override protected void onPostExecute(List<KaiYan.ItemBean> itemList) { super.onPostExecute(itemList); // 可以使用RecyclerView或ListView展示数据 for (KaiYan.ItemBean itemBean : itemList) { Log.d("1507", "type: " + itemBean.getType() + ", title: " + itemBean.getData().getTitle() + ", url" + itemBean.getData().getPlayUrl()); } } } }
package net.bwie.network.activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import com.google.gson.Gson; import net.bwie.network.R; import net.bwie.network.bean.Person; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * 当前案例: * 上传姓名和年龄,返回JSON字符串 */ public class PostActivity extends AppCompatActivity implements View.OnClickListener { protected Button mPostBtn; public static void startActivity(Context context) { context.startActivity(new Intent(context, PostActivity.class)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_post); initView(); } @Override public void onClick(View view) { if (view.getId() == R.id.post_btn) { doPost(); } } // 使用异步任务执行POST请求 private void doPost() { String url = "http://172.21.66.7:8080/postdemo"; PostTask task = new PostTask(); task.execute(url); } private void initView() { mPostBtn = (Button) findViewById(R.id.post_btn); mPostBtn.setOnClickListener(PostActivity.this); } private class PostTask extends AsyncTask<String, Void, Person> { @Override protected Person doInBackground(String... params) { String requestUrl = params[0]; // try { URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置POST请求 connection.setRequestMethod("POST"); // 设置可向服务器输出 connection.setDoOutput(true); connection.setDoInput(true); // 打开连接 connection.connect(); // 打开连接后,向服务端写要提交的参数 // 参数格式:“name=asdasdas&age=123123” StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("name=") .append("wuyanzu")// 拼接自己传入的姓名 .append("&") .append("age=") .append("123");// 拼接自己传入的年龄 // 获取向服务器写数据的输出流 connection.getOutputStream() .write(stringBuilder.toString().getBytes()); // 提交数据后,获取来自服务器的json数据 if (connection.getResponseCode() == 200) { BufferedReader br = null; br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String json = ""; String line = ""; while ((line = br.readLine()) != null) { json += line.trim(); } // 解析 Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class); return person; } } catch (Exception e) { e.printStackTrace(); Log.d("1507", e.getMessage()); } return null; } @Override protected void onPostExecute(Person person) { super.onPostExecute(person); Log.d("1507", "name:" + person.getName() + ", age: " + person.getAge()); } } }
package net.bwie.network.bean; import java.util.List; public class KaiYan { private List<ItemBean> itemList; public List<ItemBean> getItemList() { return itemList; } public void setItemList(List<ItemBean> itemList) { this.itemList = itemList; } public static class ItemBean { private String type = ""; private DataBean data; public String getType() { return type; } public void setType(String type) { this.type = type; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { private String playUrl = ""; private String title = ""; public String getPlayUrl() { return playUrl; } public void setPlayUrl(String playUrl) { this.playUrl = playUrl; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } } }
package net.bwie.network.bean; public class Person { private String name = ""; private String age = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
<?xml version="1.0" encoding="utf-8"?> <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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="net.bwie.network.activity.MainActivity"> <Button android:id="@+id/next_btn" android:text="下一页POST请求" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/get_network_data_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载网络数据"/> <Button android:id="@+id/get_pic_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取网络图片"/> <ImageView android:id="@+id/image_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <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="net.bwie.network.activity.PostActivity"> <Button android:id="@+id/post_btn" android:text="post请求" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </android.support.constraint.ConstraintLayout>
<uses-permission android:name="android.permission.INTERNET"/>
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.picasso:picasso:2.3.2'
testCompile 'junit:junit:4.12'