这两天一直想学习android网络请求方面的知识,于是仔细看了《第一行代码》有关于网络请求这一章,主要看了如何网络请求获取JSON数据,想把自己的心得记录下来。
首先,我上网选取了一个接口(url),这个接口要好,否则连不上就容易报错啦!
其次,用法详见《第一行代码》使用Http协议访问网络这一节,由于我用的是android studio
android sdk 23,不支持书中的HttpClient这个类进行访问(如果实在想用这个类的话,需要额外的导入相应的包),那么就用HttpURLConnection这个类进行访问,具体流程如下:
- URL url = new URL("http://api.androidhive.info/contacts/");
connection = (HttpURLConnection) url.openConnection();
2.设置访问网络的方式:“POST”和“GET”两种,这里采取GET方式,
connection.setRequestMethod("GET"); - connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
这一步是设置访问连接或者读取超时; - 用输入流获取服务器端返回的数据信息,
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
备注:1.既然是网络请求,不免会受到网络影响;
2.关于StringBuilder与String 的区别:
String 定义为不可变字符串,StringBuilder定义为可变字符串,可以实现字符串的拼接,如:
StringBuilder sb=StringBuilder();
sb.append("aa");
sb.append("bb");
System.out.println(sb);
此时sb为 aabb;
放上代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
private TextView responseText;
JSONArray contacts = null;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj; // 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text); sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() { // 开启线程来发起网络请求 new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://api.androidhive.info/contacts/"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream(); // 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader( new InputStreamReader(in)); StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE; // 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
parseJSON(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
private void parseJSON(String jsonData) {
try {
JSONObject jsonObj = new JSONObject(jsonData);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("contacts");
for (int i=0;i<contacts.length();i++){
JSONObject jsonObject=contacts.getJSONObject(i);
String name=jsonObject.getString("name");
String email=jsonObject.getString("email");
String address=jsonObject.getString("address"); Log.d("MainActivity","name is "+name);
Log.d("MainActivity","email is "+email);
Log.d("MainActivity","address is "+address);
}
} catch (Exception e) {
e.printStackTrace(); } }}