W / System.err: java.io.FileNotFoundException - PullRequest
0 голосов
/ 06 июня 2019
W/System.err: java.io.FileNotFoundException:http://192.168.0.102/login/register.php

Я пытаюсь отправить информацию в базу данных через устройство Android, но ... она показывает эту ошибку ...

        try {
            URL url = new URL(reg_url);

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(100000);

            OutputStream os = httpURLConnection.getOutputStream();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));


            String data = URLEncoder.encode("userid","UTF-8") +"="+ URLEncoder.encode(userid,"UTF-8")+"&"+
                    URLEncoder.encode("email","UTF-8") +"="+ URLEncoder.encode(user_email,"UTF-8")+"&"+
                    URLEncoder.encode("password","UTF-8") +"="+ URLEncoder.encode(user_pass,"UTF-8");

            bufferedWriter.write(data);

            bufferedWriter.flush();
            bufferedWriter.close();
            os.close();

Исключение:

W/System.err: java.io.FileNotFoundException:
http://192.168.0.102/login/register.php
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
at com.loginapp.logintest.background$override.doInBackground(background.java:80)
at com.loginapp.logintest.background$override.access$dispatch(background.java)
at com.loginapp.logintest.background.doInBackground(background.java)
at com.loginapp.logintest.background.doInBackground(background.java:22)

Ответы [ 2 ]

0 голосов
/ 06 июня 2019

Вы можете попробовать получить доступ к http://192.168.0.102/login/register.php в своем веб-браузере dekstop, чтобы доказать, что он действительно доступен или это правильный URL-адрес. Вы можете просто закомментировать оставшуюся часть кода в вашем файле register.php, а затем повторить что-то вроде

<?php echo 'hello'; ?> 

и посмотрите, отображается ли оно в вашем браузере. Возможно, что URL для register.php может быть неправильным.

EDIT

По просьбе Ankit я предоставлю краткое руководство по созданию Wamp онлайн. Это может помочь решить проблему Forbidden , и я также разместил ссылку на Youtube, чтобы помочь вам в дальнейшем. Мой совет: не устанавливайте очень определенный IP-адрес, такой как 192.168.{other values}, внутри вашего файла httpd.conf, как это делают некоторые блоги. Мое руководство позволяет использовать любой IP-адрес, что позволяет разрешать подключения без необходимости изменения файлов .conf.

ВАРИАНТ 1: ИСПОЛЬЗОВАНИЕ ОПЦИИ ОНЛАЙН PUT


1.  Using the Put Online Option
    There is a new option on the icon tray of wamp server if you left click on it, at the bottom you will see 'Put online'. You can enable it. 
    Though I use it, I am not sure if it makes Wamp online without prior changes to *httpd.conf* and *httpd-vhost.conf* since I had 
    already made these changes before I started using it. 
    What I know is that after changing those files, my Wamp is accessible online even without clicking 'put online' option.

2.  Go to '*Control Panel > System and Security > Windows Defender Firewall > Allow an App or feature through Windows Defender firewall*' 
    Click Allow another app and under Path, browse to the location of httpd.exe (in my case it is '*C:\wamp64\bin\apache\apache2.4.23\bin\http.exe*').
    Then select the checkboxes for 'private' and 'public' and then click ok.
3.  Restart your Wampserver and click Put online.
4.  Please note that if you have skype, then you may need to do this if you icon does not change to green:
    i.      open skype 
    ii.     then under  Tools > Connections, untick the option for "use port 80 and 443 for additional incoming connection". 
    iii.    Save and then close skype
    iv.     Restart Wampserver.
5.  Open you Windows hotspot and share it with your android phone, or vice versa.
6.  Open cmd.exe and run the command '*ipconfig*'. Get your IP address 
    e.g. 192.168.{other values}, mine is usually 192.168.137.1 but it is currently showing 192.168.43.66.
7.  In your android phone, type '*http://<that ip address from cmd>*' on your Web browser. It should load the Wampserver page on the browser. 

ВАРИАНТ 2: ИЗМЕНЕНИЕ ФАЙЛОВ «HTTPD.CONF» И «HTTPD-VHOST.CONF»


Please note that there is no deletion that is done. 
For all the lines that I have placed here, you simply need to change from some old value to a new value 
e.g require local to require granted, etc, or add a line if it is missing. 

1. Open httpd.conf file (found under '*c:\wamp64\bin\apache\apache{apache_version}\conf\httpd.conf*')
2. Save a copy of this original file somewhere else just in case of anything.
3. Locate the following lines and change them to be as below;

        ..........
        #Listen 12.34.56.78:80
        Listen 0.0.0.0:80
        Listen [::0]:80

        ..........  

        # If your host doesn't have a registered DNS name, enter its IP address here.
        ServerName localhost:80

        ..........

        # Deny access to the entirety of your server's filesystem. You must
        # explicitly permit access to web content directories in other 
        # <Directory> blocks below.
        #
        <Directory />
            AllowOverride none
            Require all granted
        </Directory>

        ..........

        DocumentRoot "${INSTALL_DIR}/www"
        <Directory "${INSTALL_DIR}/www/">
            .......
            AllowOverride all
            .......
            Require all granted
        </Directory>

        .........
        <Files ".ht*">
             Require all granted
        </Files>

        .........
        <Directory "${INSTALL_DIR}/cgi-bin">
            AllowOverride None
            Options None
            Require all granted
        </Directory>

4.  Open httpd-vhost.conf file (found under '*c:\wamp64\bin\apache\apache{apache_version}\conf\extra\httpd-vhost.conf*')
5.  Save a copy of this original file somewhere else just in case of anything.
6.  Change the code to:
    (please note that if you have other extra lines inside that are not here, please DO NOT delete them. 
     Just add what is missing and change what appears needs to be changed e.g. Require local to require all granted)

    # Virtual Hosts
    #

    <VirtualHost *:80>
        ServerName localhost
        DocumentRoot c:/wamp64/www
        <Directory  "c:/wamp64/www/">
            Options +Indexes +Includes +FollowSymLinks +MultiViews
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    #

7.  Open hosts file (path is '*C:\Windows\System32\drivers\etc\hosts*') and change or add these lines to be these 
    (you have to launch notepad or any other text editor like notepad++ as administrator so that you can be allowed to change them):
    # localhost name resolution is handled within DNS itself.
    #   127.0.0.1       localhost
    #   ::1             localhost

8.  Go to '*Control Panel > System and Security > Windows Defender Firewall > Allow an App or feature through Windows Defender firewall*' 
    Click Allow another app and under Path, browse to the location of httpd.exe (in my case it is '*C:\wamp64\bin\apache\apache2.4.23\bin\http.exe*').
    Then select the checkboxes for 'private' and 'public' and then click ok.
9.  Restart your Wampserver and everything should be okay.
10. Please note that if you have skype, then you will need to:
    i.      open skype 
    ii.     then under  Tools > Connections, untick the option for "use port 80 and 443 for additional incoming connection". 
    iii.    Save and then close skype
    iv.     Restart Wampserver.

11. Open you Windows hotspot and share it with your android phone, or vice versa.
12. Open cmd.exe and run the command '*ipconfig*'. Get your IP address 
    e.g. 192.168.{other values}, mine is usually 192.168.137.1 but it is currently showing 192.168.43.66.
13. In your android phone, type 'http://<that ip address from cmd>' on your Web browser. It should load the Wampserver page on the browser. 

Я знаю, что это не XML-код, но этот формат делает его более привлекательным для чтения. Другие полезные ссылки, которые могут вам помочь: это , это , это (содержит полезные изображения) и Как разрешить доступ к серверу Wamp Server 3.0 на другом компьютере | как решить "Запрещенный" доступ wamp - ссылка на Youtube :

0 голосов
/ 06 июня 2019

Вы можете получить FileNotFoundException, если получите неправильный ответ от сервера (код ответа! = HttpURLConnection.HTTP_OK).

int responseCode = httpURLConnection.getResponseCode();

if (responseCode != HttpURLConnection.HTTP_OK) {
    inputStream = httpURLConnection.getErrorStream();
} else {
    inputStream = httpURLConnection.getInputStream();
}
...