Bri*_*ier 6 java http android-studio okhttp3
我正在使用Android Studio,我花了几个小时试图在我的MainActivity.java文件中做一个简单的HTTP请求,并尝试了多种方法,并看到了很多关于这个主题的网页,但却无法弄清楚.
当我尝试OkHttp时,我收到一条关于无法在主线程上执行此操作的错误.现在我试着这样做:
public static String getUrlContent(String sUrl) throws Exception {
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}
Run Code Online (Sandbox Code Playgroud)
我将该方法直接放在MainActivity.java中,我的click事件从MainActivity.java中的另一个方法执行它:
try {
String str = getUrlContent("https://example.com/WAN_IP.php");
displayMessage(str);
}
catch(Exception e){
displayMessage(e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)
但是现在没有崩溃,我可以告诉该行抛出的异常是"BufferedReader",但是e.getMessage()是空白的.
我是Android Studio和Java的新手,所以请善待并帮助我解决这个非常基本的问题.最终我需要向服务器发送请求,看起来OkHttp是最好的方法,但我没有在网上随处可见的Android Studio中找到OkHttp的"Hello World".
Nic*_*art 17
您不应该在主线程上发出网络请求.延迟是不可预测的,它可能会冻结用户界面.
如果您使用HttpUrlConnection主线程中的对象,Android会通过抛出异常来强制执行此行为.
然后,您应该在后台发出网络请求,然后在主线程上更新UI.该AsyncTask班可用于该用途的情况下,非常方便!
private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}
Run Code Online (Sandbox Code Playgroud)
你以这种方式开始这个过程:
new GetUrlContentTask().execute(sUrl)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29048 次 |
| 最近记录: |