HTTPURLConnection
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(v->{
getHTTPRes();
});
}
private void getHTTPRes(){
new Thread(()->{
HttpURLConnection connection=null;
try {
URL url=new URL("https://cn.bing.com/");
connection= (HttpURLConnection) url.openConnection();
//设置连接的请求方法和延迟时限
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//获取输入流
InputStream inputStream = connection.getInputStream();
//繁琐的IO操作
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder builder=new StringBuilder();
while((line=reader.readLine())!=null){
builder.append(line);
Log.d("mes", "getHTTPRes: "+line);
}
updateUI(builder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
connection.disconnect();
}
}).start();
}
private void updateUI(String str){
//这是activity中的方法
runOnUiThread(()->{
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(str);
});
}
}
这里遇到一个问题,每次重新运行程序只是在虚拟机中重新编译了app,如果要改变权限需要卸载了重新下载一遍。
OKHTTP
采用OKHTTP可以实现避免繁琐恼人的IO操作,不过这个库最好用kotlin写,因为调用的方法符合kotlin的规范,可能会让写多了Java的人感到困惑。
private void getHTTPResWithOkhttp() {
new Thread(() -> {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://cn.bing.com/").build();
try {
Response response = client.newCall(request).execute();
updateUI(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
HTTP请求工具类
可以发现请求并获取HTTP报文的步骤是可以作为一个模块分离的,因此编写请求工具类,需要注意的是安卓的网络访问请求必须放在子线程中进行,子线程中无法返回值,因此不能单独在工具类的方法中开启子线程返回所需报文,可以采用回调接口的方式来实现子线程请求。
interface HTTPCallBack{
public void onFinish(String res);
public String onError(String res);
}
class HTTPRequest{
public static void getRequest(String uri,HTTPCallBack callBack){
new Thread(()->{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(uri).build();
try {
Response response= client.newCall(request).execute();
callBack.onFinish(response.body().string());
} catch (IOException e) {
callBack.onError(e.toString());
}
}).start();
}
}
HTTPRequest.getRequest("https://cn.bing.com/", new HTTPCallBack() {
@Override
public void onFinish(String res) {
updateUI(res);
}
@Override
public String onError(String res) {
return null;
}
});
不过在OkHttp里面 ,提供了开好子线程的请求方法enqueue,这样就没必要自己开启子线程了。
|