php-file auf einem server aufrufen über http get - file wird nicht gefunden!

  • Antworten:16
Peter Staudigel
  • Forum-Beiträge: 20

05.05.2015, 09:39:40 via Website

hallo, habe mal wieder nen problem...

also habe local bei mir meine app getestet it datenbank und allem drum und drann
dort hatte ich ja das problem:
wenn ich ein php-file aufgerufen habe über http get das nicht mit http//localhost/.... ging,
sondern ich musste für localhost eine pc-ip eintragen.

nun versuche ich das ganze online zu achen, also eine dateien liegen jetzt bei bytehost.
der link zur datei ist:
"http"+ "://"+"peetwonder.byethost16.com/login.php"

wenn ich das im firefox eingebe erreiche ich das file auch ohne Probleme
nur über die app (weder Emulator noch aufm Handy) komm ich nicht an das file wie es mir scheint.

der Fehler ist aus einer Sicht genau der selbe wie ich es schon mal hatte, nur wei ich nicht wie ich bei bytehost da rann kommen soll.

danke schon mal für eure Hilfe :)
hier noch logcat:

05-05 00:09:57.798 2690-2709/com.example.mysqltest W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-05 00:09:57.798 2690-2709/com.example.mysqltest W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa67ea560, error=EGL_SUCCESS
05-05 00:09:57.848 2690-2702/com.example.mysqltest I/art﹕ Background sticky concurrent mark sweep GC freed 3102(139KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 1774KB/2010KB, paused 6.408ms total 94.079ms
05-05 00:09:58.105 2690-2710/com.example.mysqltest E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Failed of type java.lang.String cannot be converted to JSONObject
05-05 00:09:58.105 2690-2710/com.example.mysqltest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.mysqltest, PID: 2690
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:126)
at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
05-05 00:10:00.802 2690-2690/com.example.mysqltest E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3595a308 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:104)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.mysqltest.Login.onClick(Login.java:83)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

— geändert am 05.05.2015, 09:40:29

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2015, 13:17:56 via Website

Hallo,
ich denke, den String du parsen willst ist null daduch wird auch die Exception ausgelöst.
Da stimmt irgendwas mit dem Download nicht.
Zeig mal den Code.

LG

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

05.05.2015, 16:28:08 via Website

ok,
also parsen:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}


// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

so und so ruf ich das auf:

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

wobei Url deklariert ist als(vor der url steht noch http...):

private static final String LOGIN_URL = "peetwonder.byethost16.com/login.php";

ansonsten hier nochal der ganze Code von dem Aufruf:

package com.example.mysqltest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

private EditText user, pass;
private Button mSubmit, mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// testing on Emulator:
private static final String LOGIN_URL = "peetwonder.byethost16.com/login.php";


// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ADMIN = "admin";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // setup input fields
    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);

    // setup buttons
    mSubmit = (Button) findViewById(R.id.login);
    mRegister = (Button) findViewById(R.id.register);

    // register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.login:
        new AttemptLogin().execute();
        break;
    case R.id.register:
        Intent i = new Intent(this, Register.class);
        startActivity(i);
        break;

    default:
        break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                // save user data
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                Intent intent = new Intent(Login.this, ReadComments.class);
                intent.putExtra("ADMIN", json.getInt(TAG_ADMIN));
                finish();
                startActivity(intent);
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2015, 16:46:17 via Website

er fehler tritt hier auf:
jObj = new JSONObject(json);

ich denke dass du da von deinem HTTPClient oder StringBuilder ein Null Object zurückbekommst.
Entweder mit einer If auf null prüfen oder die Funktion mit dem String builder etc. debuggen ändern und fixen.

Lg

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

05.05.2015, 17:06:21 via Website

jup hab da as gefunden...

aber verstehe nicht ganz warum.

wenn ich das über die app aufrufe gibt mir die seite das zurück

 <html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /login.php
on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache Server at www.peetwonder.byethost16.com Port 80</address>
</body></html>

aber was ist ein errordocument?

— geändert am 05.05.2015, 17:07:15

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2015, 17:36:09 via Website

Also ich würde erstmal die url anpassen:

private static final String LOGIN_URL = "http://www.peetwonder.byethost16.com/login.php";

Ein errordokument ist ist meist eine HTML Seite die angezeigt wird wenn ein Fehler auftritt.
In deinem Fall ist kein Error Dokument für den Error 404/403 vorhanden und deswegen die Meldung.
Was mir eigentlich komisch vorkommt, denn im Browser tut die Seite, warum du allerdings einen Error zurückbekommst kann ich dir gerade nicht beantworten.

LG

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

05.05.2015, 17:44:23 via Website

jup das mit der url (www.) hab ich schon gemacht. Ist mir selber schon aufgefallen

— geändert am 05.05.2015, 17:48:09

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

05.05.2015, 23:50:23 via Website

also das Problem besteht weiterhin...

habe aber durch Zufall etwas raus bekommen:

mit www.peetwonder.byethost16.com
kommt man (insofern man es hat immer auf die index.php)
also ohne "/login.php"

ich mache somit erstmal alles in der index.php und schicke ne Variable mit. Nach der entscheide ich, welchen Teil ich dann ausführe...
ist nicht toll aber geht, vielleicht hat ja doch noch irgendwann jemand ein Tipp zu der Sache.

mfG Peter :)

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

06.05.2015, 06:29:24 via App

soganz uabe ich das nicht verstanden. Aber du musst doch fürs login ne richtige Api in PHP bereitstellen wo du dann eine Logindaten hinschickst un einen OK oder Error zurückbekommst.
Das funktioniert ja nicht einfach nur übers normale Webseitenskript dafür musst du ne eigene Datei machen.

— geändert am 06.05.2015, 06:29:42

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

06.05.2015, 07:51:27 via Website

genau und die datei ist index.php

und diese ruft wiederum die config.inc.php auf....

Antworten
Ju Ku
  • Forum-Beiträge: 72

07.05.2015, 14:19:50 via Website

Wenn der WebServer so konfiguriert ist, dass er nur bestimmten Clients, z.B. Clients, die sich vorher authentifiziert haben oder eine bestimmte IP besitzen, eine File ausliefert, dann kann ein Forbidden Error geworfen werden, falls der Client nicht authentifiziert ist.
Der Fehler 404 Not Found wird geworfen, wenn die File auf dem Server nicht vorhanden ist.
Ich vermute mal, dass du deine WebServer Configuration ändern musst.

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

07.05.2015, 21:55:56 via Website

hab ich auch schon versucht, hab alle möglichen freigaben gesetzt die ich gefunden hab...
leider auch ohne erfolg. Wobei ich mir ziehmlich sicher bin das es an dem Server liegt :)

Antworten
Ju Ku
  • Forum-Beiträge: 72

08.05.2015, 12:45:01 via Website

Ich vermute mal, die Domain zeigt nicht auf /, sondern auf ein anderes directory, in welchem sich aber die File nicht befindet.
Was ist denn der DocumentRoot?

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

09.05.2015, 14:34:05 via Website

das verstehe ich nicht ganz?

wenn ich den link für das entsprechende file direkt im browser eingebe komme ich auch auf das file.
nur über die app nicht bzw. es gibt ir ja nur zurück das ich ich ohl nicht die berechtigung dafür hätte


403 Forbidden

Forbidden

You don't have permission to access /login.php on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.



Apache Server at www.peetwonder.byethost16.com Port 80

Antworten
Ju Ku
  • Forum-Beiträge: 72

09.05.2015, 14:37:17 via Website

Wenn ich die Website http://www.peetwonder.byethost16.com/login.php aufrufe, erhalte ich ebenfalls einen Fehler 404 Not Found.
Die File existiert auf dem Server also nicht.

Antworten
Peter Staudigel
  • Forum-Beiträge: 20

09.05.2015, 16:58:43 via Website

habe es mitlerweile gelöscht :D, aber ich mach es dir mal eben drauf^^

— geändert am 09.05.2015, 17:05:00

Antworten