使用php和mysql的http请求创建android应用程序

时间:2013-10-15 16:59:48

标签: php android mysql httprequest json

我有一个简单的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;
    }
}

SecondaryActivity

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);
}

?>

1 个答案:

答案 0 :(得分:4)

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

即。

http://10.0.2.2/studentservice/StudentService/getStudentByID.php 
PC浏览器上的

也会产生404错误。您确定网址是否正确?也许你有一个studenservice太多?