尊重原創(chuàng)霜浴,從我做起。本文參考郭霖《第一行代碼》屯烦,第2版坷随。
一房铭、網(wǎng)絡(luò)請求
1.使用RLConnection
private void sendRequestWithHttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try{
URL url = new URL("http://www.baidu.com");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
InputStream in = httpURLConnection.getInputStream();
//對獲得的流進(jìn)行讀取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
response.append(line);
}
//處理相應(yīng)
handleResponse(response.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
}
}
}).start();
}
2.使用okHttp
private void sendRequestWithOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Response response = okHttpClient.newCall(request).execute();
String responseData = response.body().string();
handleResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
二驻龟、對相應(yīng)結(jié)果進(jìn)行處理
若是要進(jìn)行ui操作,必須要返回主線程
//處理網(wǎng)絡(luò)請求的結(jié)果
private void handleResponse(String responseData){
runOnUiThread(new Runnable() {
@Override
public void run() {
//更新UI
tv.setText(responseData);
}
});
}