以Swift发送HTTP请求并获得1001,999错误

时间:2023-01-22 17:51:16

I have been given the following lines of code, which aim to send a value to an IP in Java. According to my understanding, it seems to be a GET method. But, there is no parameter being sent. Feel free to correct me, as I am fully illiterate in android programming.

我得到了以下几行代码,它们的目的是向Java中的IP发送值。根据我的理解,这似乎是一种获取方法。但是,没有发送参数。请随意纠正我,因为我对android编程完全不了解。

private class Background_get extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
    try {
      /* Change the IP to the IP you set in the arduino sketch */
      URL url = new URL("http://192.168.43.142/?" + params[0]);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(10000);
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      StringBuilder result = new StringBuilder();
      String inputLine;
      while ((inputLine = in.readLine()) != null)
        result.append(inputLine).append("\n");
      in.close();
      connection.disconnect();
      return result.toString();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}

Receiver of this is an arduino and the way it processes sent data is through checking and comparing the last character. For further clarification, please refer to the following lines :

这是一个arduino,它处理发送数据的方式是通过检查和比较最后一个字符。如需进一步澄清,请参阅以下几行:

  char c = client.read();
        Serial.write(c);
        buffered +=c;
        if(buffered.endsWith("O")){ // this is for TV
           //digitalWrite(pin2,HIGH);
           irsend.sendPanasonic(0x4004,0x100BCBD);    
           delay(100);
         } else if (buffered.endsWith("X")) {
          irsend.sendPanasonic(0x4004,0x1004C4D); 
         } else if (buffered.endsWith("P")) {
          irsend.sendPanasonic(0x4004,0x1000405); 
         } else if (buffered.endsWith("M")) {
          irsend.sendPanasonic(0x4004,0x1008485); 
         } else if (buffered.endsWith("1")) 

What I have currently done here is first to setup the info.plist for the HTTP communication like so :

我现在做的是首先设置信息。HTTP通信的plist如下:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <false/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>192.168.43.142</key> 
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
        </dict>
    </dict>

And here I define my IP address :

这里我定义了IP地址:

enum API : String {
    case url = "http://192.168.43.142/?"

}

and I use it in the following way :

我使用它的方式如下:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         var httpRequest = API.url.rawValue
        let clicked_btn = indexPath.row
        switch clicked_btn {

        case 0 :

            httpRequest = "\(httpRequest)CP"


        case 1 :
           httpRequest = "\(httpRequest)1"


        case 2 :
            httpRequest = "\(httpRequest)2"

        case 3 :
            httpRequest = "\(httpRequest)3"

        case 4 :
            httpRequest = "\(httpRequest)CM"

        case 5:
           httpRequest = "\(httpRequest)4"

        case 6 :
            httpRequest = "\(httpRequest)5"

        case 7 :
            httpRequest = "\(httpRequest)6"
        case 8 :
            httpRequest = "\(httpRequest)P"

        case 9 :
            httpRequest = "\(httpRequest)7"

        case 10 :
            httpRequest = "\(httpRequest)8"

        case 11:
            httpRequest = "\(httpRequest)9"

        case 12 :
            httpRequest = "\(httpRequest)M"

        case 13 :
            httpRequest = "\(httpRequest)X"
        case 14 :
            httpRequest = "\(httpRequest)0"

        case 15 :
            httpRequest = "\(httpRequest)O"


        default :
            print("deaf")
            break
    }
        //send the HTTP Request :
        print( "my http request is ====> \(httpRequest)")

        let url = URL(string: "\(httpRequest)")!
        let request = URLRequest(url: url)

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            //do stuff with data, response, error
            print("Response : \(response)")


        }

        task.resume()

}

The problem here is that I keep getting the following error in the console.I have no idea where am I making mistake. I have checked most of the other similar questions but could not figure any answer.

这里的问题是我在控制台中不断得到以下错误。我不知道我在哪里出错。我检查了其他大部分类似的问题,但没有找到任何答案。

 my http request is ====> http://192.168.43.142/?O
    2018-03-02 19:06:43.749016+0800 Master_Project[1687:584006] Task <8BCA1C8B-6571-491D-85D7-97BE6633E720>.<1> finished with error - code: -1001
    2018-03-02 19:06:43.766883+0800 Master_Project[1687:584006] Task <8BCA1C8B-6571-491D-85D7-97BE6633E720>.<1> HTTP load failed (error code: -999 [1:89])
    Response : nil

I strongly appreciate your kind help. It's worth mentioning that I have tried this both on simulator and the real device and they both ended up giving me the same error 以Swift发送HTTP请求并获得1001,999错误

我非常感谢你的帮助。值得一提的是,我在模拟器和真实设备上都试过了,结果他们都给了我同样的错误

1 个解决方案

#1


1  

The error code -1001 mean that your connection timed out. Looks like your setup fails to connect to the server. For testing purpose you could make your NSAppTransportSecurity settings simpler and just set NSAllowsArbitraryLoads to true; if the connection works this way you know it's related to the configuration.

错误代码-1001表示连接超时。看起来您的设置未能连接到服务器。为了测试目的,您可以使NSAppTransportSecurity设置更简单,并将nsallowsarbitraryload设置为true;如果连接以这种方式工作,您就知道它与配置有关。

Here's a list of some network-related error codes.

以下是一些与网络相关的错误代码。

#1


1  

The error code -1001 mean that your connection timed out. Looks like your setup fails to connect to the server. For testing purpose you could make your NSAppTransportSecurity settings simpler and just set NSAllowsArbitraryLoads to true; if the connection works this way you know it's related to the configuration.

错误代码-1001表示连接超时。看起来您的设置未能连接到服务器。为了测试目的,您可以使NSAppTransportSecurity设置更简单,并将nsallowsarbitraryload设置为true;如果连接以这种方式工作,您就知道它与配置有关。

Here's a list of some network-related error codes.

以下是一些与网络相关的错误代码。