尊重原创,从我做起。本文参考郭霖《第一行代码》,第2版。
一、网络请求
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();
//对获得的流进行读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
response.append(line);
}
//处理相应
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();
}
二、对相应结果进行处理
若是要进行ui操作,必须要返回主线程
//处理网络请求的结果
private void handleResponse(String responseData){
runOnUiThread(new Runnable() {
@Override
public void run() {
//更新UI
tv.setText(responseData);
}
});
}