使用应用程序发送 HTTP 请求 - AndroidStudio

我想在按下按钮到 ESP8266 时从我的 android 应用程序发送 HTTP 请求,该 ESP8266 正在等待任何网页被访问,但是我希望我的 android 应用程序实际上没有打开网页,而只是“发送一个 HTTP要求”

现在我正在使用;

startActivity(new Intent(Intent.ACTION_QUICK_VIEW, Uri.parse("http://192.168.1.201/onled")));

它正在工作,但显然它正在打开网页......

有人对如何解决我的问题有好的建议吗?我是 Java 新手。


潇潇雨雨
浏览 239回答 3
3回答

慕勒3428872

new AsyncTask<Void,Void,Void>(){&nbsp; &nbsp; &nbsp; &nbsp; private Exception exception;&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; protected Void doInBackground(Void... voids) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; URL url= new URL("http://yourserveraddress/resource.extension");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpURLConnection con= (HttpURLConnection) url.openConnection();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //write additional POST data to url.getOutputStream() if you wanna use POST method&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }catch (Exception ex){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.exception=ex;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; protected void onPostExecute(Void aVoid) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super.onPostExecute(aVoid);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }.execute();

慕桂英546537

有很多方法可以从应用程序发送 HTTP 请求。例如使用HttpURLConnectionwithGET方法,您可以按如下方式进行:&nbsp;StringBuilder content = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; URL u1 = new URL(url);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpURLConnection uc1 = (HttpURLConnection) u1.openConnection();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (uc1.getResponseCode()==HttpURLConnection.HTTP_OK) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream is = uc1.getInputStream();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String line;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((line = br.readLine()) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; content.append(line).append("\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }//other codes

回首忆惘然

您应该创建 HTTP 连接和 HTTP 请求。您可以通过以下几种方式做到这一点:HttpURLConnection在 Java 中使用本机可用 - 有关详细信息,请参阅本教程:https&nbsp;:&nbsp;//www.mkyong.com/java/how-to-send-http-request-getpost-in-java/使用专用库,它以稍微好一点的方式做同样的事情 - 例如OkHttp请记住,发送 HTTP 请求是非确定性操作,您应该在单独的非 UI 线程中执行它以保持 UI 畅通。您可以通过AsyncTask 来完成,这是最简单的解决方案,但您也可以将RxJava与RxAndroid或其他方法一起使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java