【问题标题】:creating android application using http request with php and mysql使用带有 php 和 mysql 的 http 请求创建 android 应用程序
【发布时间】:2013-10-23 14:09:18
【问题描述】:

我有一个简单的 android 应用程序,我在其中使用 http 请求和 php mysql 但是LogCat显示的问题是php文件的路径有错误。

谁能帮我解决这个问题??

LogCat

10-15 16:42:03.380: I/dalvikvm(1596): threadid=3: reacting to signal 3
10-15 16:42:03.530: I/dalvikvm(1596): Wrote stack traces to '/data/anr/traces.txt'
10-15 16:42:03.860: D/gralloc_goldfish(1596): Emulator without GPU emulation detected.
10-15 16:42:03.880: I/dalvikvm(1596): threadid=3: reacting to signal 3
10-15 16:42:03.890: I/dalvikvm(1596): Wrote stack traces to '/data/anr/traces.txt'
10-15 16:42:08.550: E/Error befor http(1596): Error before the http request
10-15 16:42:08.890: E/Student Data(1596): <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
10-15 16:42:08.890: E/Student Data(1596): <html><head>
10-15 16:42:08.890: E/Student Data(1596): <title>404 Not Found</title>
10-15 16:42:08.890: E/Student Data(1596): </head><body>
10-15 16:42:08.890: E/Student Data(1596): <h1>Not Found</h1>
10-15 16:42:08.890: E/Student Data(1596): <p>The requested URL /studentservice/StudentService/getStudentByID.php was not found on this server.</p>
10-15 16:42:08.890: E/Student Data(1596): </body></html>
10-15 16:42:08.940: I/dalvikvm(1596): threadid=3: reacting to signal 3
10-15 16:42:08.960: I/dalvikvm(1596): Wrote stack traces to '/data/anr/traces.txt'
10-15 16:42:09.440: I/dalvikvm(1596): threadid=3: reacting to signal 3
10-15 16:42:09.450: I/dalvikvm(1596): Wrote stack traces to '/data/anr/traces.txt'

HttpManager

package com.lebdev.fitguide.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpManager {

    private InputStream inputStream;
    private HttpClient httpClient;
    private HttpResponse httpResponse;
    private HttpPost httpPost;
    private HttpEntity httpEntity;
    private StringBuilder result;

    public HttpManager() {

        this.inputStream = null;
        this.httpClient = null;
        this.httpResponse = null;
        this.httpPost = null;
        this.httpEntity = null;
        this.result = null;

    }

    public String getResponseFromURL(String url, List<NameValuePair> params) {

        try {

            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            inputStream = httpEntity.getContent();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "UTF-8"), 8);
            result = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                result.append(line + "\n");
            }
            inputStream.close();
            return result.toString();

        } catch (Exception ex) {
            Log.e("Bufferring Error, ", ex.getMessage());
        }

        return null;
    }

}

JsonObjectMapper

package com.lebdev.fitguide.om;

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

import org.json.JSONObject;

import android.util.Log;

import com.lebdev.fitguide.businessModel.Student;

public class JsonObjectMapper {

    public static Student jsonToStudent(JSONObject jsonObject) {

        Student std = null;

        try {

            std = new Student(jsonObject.getJSONArray("Student")
                    .getJSONObject(0).getString("Name"),
                    Integer.parseInt(jsonObject.getJSONArray("Student")
                            .getJSONObject(0).getString("Index")),
                    Integer.parseInt(jsonObject.getJSONArray("Student")
                            .getJSONObject(0).getString("ID")));

        } catch (Exception ex) {
            Log.e("Error Json Converter", ex.getMessage());
        }

        return std;
    }

    public static List<Student> jsonToStudentList(JSONObject jsonObject) {

        List<Student> stdList = new ArrayList<Student>();
        try {

            for (int i = 0; i < jsonObject.getJSONArray("Student").length(); i++) {

                stdList.add(new Student(jsonObject.getJSONArray("Student")
                        .getJSONObject(i).getString("Name"), Integer
                        .parseInt(jsonObject.getJSONArray("Student")
                                .getJSONObject(i).getString("Index")), Integer
                        .parseInt(jsonObject.getJSONArray("Student")
                                .getJSONObject(i).getString("ID"))));
            }
        } catch (Exception ex) {

            Log.e("Error Json Converter", ex.getMessage());
        }

        return stdList;
    }
}

次要活动

package com.lebdev.fitguide.activities;

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

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

import com.lebdev.fitguide.businessModel.Student;
import com.lebdev.fitguide.controller.HttpManager;
import com.lebdev.fitguide.controller.JSONParser;
import com.lebdev.fitguide.om.JsonObjectMapper;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class SecondaryActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_secondary);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("sid", "2"));

        Log.e("Error befor http", "Error before the http request");

        /*
        JSONObject jsonObj = JSONParser
                .parseJSONFromString(new HttpManager()
                        .getResponseFromURL(
                                "http://10.0.2.2/studentservice/StudentService/getStudentByID.php",
                                params));

        Log.e("Error after http", "Error after the http request");

        Student std = JsonObjectMapper.jsonToStudent(jsonObj);

        Log.e("STUDENT DATA", "ID:" + std.getID() +     "Name:" + std.getName());

        */

         HttpManager httpManager = new HttpManager();
        String result = httpManager.getResponseFromURL("http://10.0.2.2/studentservice/StudentService/getStudentByID.php",
                params);
        Log.e("Student Data", result);

/*
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            TextView lblMessage = (TextView) findViewById(R.id.lblSentMessage);
            Student student = bundle.getParcelable("Student");

            lblMessage.setText("I 've recieved a student with a name "
                    + student.getName() + " and has a Subject "
                    + student.getSubjects().get(0).getName() + " with a grade "
                    + student.getSubjects().get(0).getGrade());
        }
*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.secondary, menu);
        return true;
    }

}

getStudentByID.PHP

<?php
require_once '../ConnectionManager.php';

$response = array();
$db = connectionManager::getInstance();

if(isset($_POST["sid"]))
{
 $id = $_POST["sid"];
 $result = mysql_query("SELECT * FROM student WHERE ID = $id");

 if(!empty($result))
 {
    if(mysql_num_rows($result) >0)
    {
      $row = mysql_fetch_array($result);

     $student = array();
     $student["ID"] = $row["ID"];
     $student["Index"] = $row["Index"];
     $student["Name"] = $row["Name"];

    $response ["success"] = 1;
    $response["student"] = array();

    array_push($response["student"], $student);
    echo json_encode($response);
    }
    else
    {
     $response["success"] = 0;
     $response["message"] = "No Student found with this ID!!";
     echo json_encode($response);
    }
 }
 else
 {
    $response["success"] = 0;
    $response["message"] = "No Student found with this ID!!";
    echo json_encode($response);
 }

}
else
{
    $response["success"] = 0;
    $response["message"] = "Required feild(s) is missing!!";
    echo json_encode($response);
}

?>

【问题讨论】:

  • 看起来它只是一个 404 未找到...你可以从浏览器手动点击它吗?
  • 您是否阅读了第一段示例文本中的堆栈跟踪?您从 Android 访问的 URL 在服务器上不存在,从而产生 404-not found 错误消息。
  • 我在我的电脑上尝试了浏览器,它工作正常,只是我将 10.0.2.2 更改为 127.0.0.1 但在模拟器上它给了我之前描述的这个错误

标签: php android mysql httprequest json


【解决方案1】:

404 表示未找到请求的页面。所以我猜如果你在网络浏览器上请求相同的 URL,那么你会得到同样的错误。

即

http://10.0.2.2/studentservice/StudentService/getStudentByID.php 

在您的 PC 浏览器上也应该产生 404 错误。您确定网址正确吗?也许你有太多的学生服务?

【讨论】:

  • @LebDev 你在同一个网络上吗?如果您的手机使用 3G,那么您将无法访问 10.0.0.2 地址。手机和电脑需要在同一个网络上。如果可能,您可能想在同一网络上的另一台 PC 上尝试它,看看是否在那里遇到相同的错误。否则接下来的步骤是 1. 使用 GET 请求(如果您使用没有 FORM 的浏览器,则使用该请求) 2. 在服务器计算机上运行 wireshark 并找出 PC 浏览器请求和移动请求之间的区别。跨度>
  • @RaB I M 使用模拟器测试应用程序,使其在同一个网络上并且仍然有同样的问题mmmm
  • 您也可以在内置浏览器上尝试相同的 URL,看看是否也有 404。否则,唯一剩下的选择是运行 wireshark 并检查数据包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多