這兩天一直想學(xué)習(xí)android網(wǎng)絡(luò)請(qǐng)求方面的知識(shí)上渴,于是仔細(xì)看了《第一行代碼》有關(guān)于網(wǎng)絡(luò)請(qǐng)求這一章蝉稳,主要看了如何網(wǎng)絡(luò)請(qǐng)求獲取JSON數(shù)據(jù)挚赊,想把自己的心得記錄下來藻三。
首先洪橘,我上網(wǎng)選取了一個(gè)接口(url),這個(gè)接口要好,否則連不上就容易報(bào)錯(cuò)啦棵帽!
其次熄求,用法詳見《第一行代碼》使用Http協(xié)議訪問網(wǎng)絡(luò)這一節(jié),由于我用的是android studio
android sdk 23逗概,不支持書中的HttpClient這個(gè)類進(jìn)行訪問(如果實(shí)在想用這個(gè)類的話弟晚,需要額外的導(dǎo)入相應(yīng)的包),那么就用HttpURLConnection這個(gè)類進(jìn)行訪問逾苫,具體流程如下:
- URL url = new URL("http://api.androidhive.info/contacts/");
connection = (HttpURLConnection) url.openConnection();
2.設(shè)置訪問網(wǎng)絡(luò)的方式:“POST”和“GET”兩種卿城,這里采取GET方式,
connection.setRequestMethod("GET"); - connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
這一步是設(shè)置訪問連接或者讀取超時(shí)铅搓; - 用輸入流獲取服務(wù)器端返回的數(shù)據(jù)信息瑟押,
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
備注:1.既然是網(wǎng)絡(luò)請(qǐng)求,不免會(huì)受到網(wǎng)絡(luò)影響星掰;
2.關(guān)于StringBuilder與String 的區(qū)別:
String 定義為不可變字符串多望,StringBuilder定義為可變字符串,可以實(shí)現(xiàn)字符串的拼接氢烘,如:
StringBuilder sb=StringBuilder();
sb.append("aa");
sb.append("bb");
System.out.println(sb);
此時(shí)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; // 在這里進(jìn)行UI操作怀偷,將結(jié)果顯示到界面上
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() { // 開啟線程來發(fā)起網(wǎng)絡(luò)請(qǐng)求 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(); // 下面對(duì)獲取到的輸入流進(jìn)行讀取
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; // 將服務(wù)器返回的結(jié)果存放到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(); } }}