简体   繁体   English

url.openConnection(); 实际上没有被调用

[英]url.openConnection(); is not actually invoked

Im building a graduation project for my collage about "Smart Homes, Home Automation System" implemented with Arduion on a mock-up structure. 我为拼贴画设计了一个毕业项目,该项目与Arduion在模型结构上实现的“智能家居,家庭自动化系统”有关。

To have the full image, the Arduaio takes the pin number via a get request to switch on or of a specific home device. 为了获得完整的图像,Arduaio通过获取请求来打开特定家用设备的针脚号。

its all cool when i send the HTTP request from any browser, but when i use the 当我从任何浏览器发送HTTP请求时,一切都很酷,但是当我使用

openConnection();

method, it's like something never happens, but when i use it to get some data about the home rooms and its devices it's working greatly. 方法,就像从未发生过任何事,但是当我使用它来获取有关家庭房间及其设备的一些数据时,它的工作效率很高。

i already gave the app the permission to access the internet. 我已经授予该应用访问互联网的权限。

the code from a simple project i made just to solve this praticualy problem: 我为解决这个普遍存在的问题而编写的一个简单项目中的代码:

MainActivity.java MainActivity.java

package com.bitsandbytes.xemma_pc.newprototype;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SendRequest().execute(); 
            }
        });
    }

    private static class SendRequest extends AsyncTask <Void,Void,Void>{

        @Override
        protected Void doInBackground(Void... params) {
            HttpURLConnection httpURLConnection = null ;
            URL url ;
            try {
                url = new URL("http://192.168.1.143/pin=13");
                httpURLConnection = (HttpURLConnection) url.openConnection();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                httpURLConnection.disconnect();
            }

            return null;
        }
    }

}

activity_main.xml activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bitsandbytes.xemma_pc.newprototype.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Press it to Test it"
        android:id="@+id/textView"
        android:layout_marginTop="154dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pin 13"
        android:id="@+id/button"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

AndroidManifist.xml AndroidManifist.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bitsandbytes.xemma_pc.newprototype">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

i appreciate the help and the tips in advance. 我先感谢帮助和提示。

EDIT: thanks you guys for helping me, but what it really helped me was using the getResponseMessage() method, and it works greatly :D i didn't have to use .connect method to get some JSON strings before, but it was working. 编辑:谢谢你们对我的帮助,但真正帮助我的是使用getResponseMessage()方法,它的工作原理非常好:D我以前不必使用.connect方法来获取一些JSON字符串,但它确实有效。 anyway, thanks for the help! 无论如何,谢谢您的帮助!

openConnection just parses the URL and creates the appropriate URLConnection subclass. openConnection只是解析URL并创建适当的URLConnection子类。 Network I/O doesn't happen until you send or receive something. 在您发送或接收消息之前,不会发生网络I / O。

You need to read the data and then network IO will occur. 您需要读取数据,然后将发生网络IO。

String response = "";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set Method here
conn.setRequestMethod("POST");
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String line= "";
while ((line= br.readLine()) != null) {
   response += line;
}
conn.disconnect();

URL.openConnection() only returns a URLConnection to the specified resource. URL.openConnection()仅将URLConnection返回到指定资源。

You can open an actual connection to that resource by calling the connect() method of that particular URLConnection . 您可以通过调用特定URLConnectionconnect()方法来打开与该资源的实际连接。

For example: 例如:

HttpURLConnection connection = (HttpURLConnection) someUrl.openConnection();
connection.connect();

Operations that require a connection (like getInputStream() or getOutputStream() ) will implicitly call connect() , so explicitly calling it before such operations is not necessary: 需要连接的操作(如getInputStream()getOutputStream() )将隐式调用connect() ,因此无需在此类操作之前显式调用它:

HttpURLConnection connection = (HttpURLConnection) someUrl.openConnection();
connection.connect(); // this is redundant
connection.getInputStream(); // getInputStream() will call connect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM