如何在MainActivity.java中创建简单的HTTP请求? (Android Studio)

我正在使用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; } 

我将该方法直接放在MainActivity.java中,我的click事件从MainActivity.java中的另一个方法执行它:

 try { String str = getUrlContent("https://example.com/WAN_IP.php"); displayMessage(str); } catch(Exception e){ displayMessage(e.getMessage()); } 

但是现在没有崩溃,我可以告诉在线路上抛出的exception是“BufferedReader”,但是e.getMessage()是空白的。

我是Android Studio和Java的新手,所以请善待并帮助我解决这个非常基本的问题。 最终我需要向服务器发送请求,似乎OkHttp是最好的方法,但我没有在网上随处可见的Android Studio中找到OkHttp的“Hello World”。

您不应该在主线程上发出网络请求。 延迟是不可预测的,它可能会冻结用户界面。

如果您使用主线程中的HttpUrlConnection对象,Android会通过抛出exception来强制执行此行为。

然后,您应该在后台发出网络请求,然后更新主线程上的UI。 AsyncTask类对于这个用例非常方便!

 private class GetUrlContentTask extends AsyncTask { 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); } } 

你以这种方式开始这个过程:

 new GetUrlContentTask().execute(sUrl) 

看看这个答案。 无法在主线程中打开HTTP连接(这就是你遇到第一个错误的原因)并且使用AsyncTask是处理这个问题的好方法

如果您使用okhttp然后调用aysnc尝试波纹管代码

  private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.setConnectTimeout(15, TimeUnit.SECONDS); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { Log.e(responseHeaders.name(i) , responseHeaders.value(i)); } Log.e("response",response.body().string()); } }); }