繁体   English   中英

从Android连接到PHP服务器时出现错误

[英]Getting an error when connecting from android to PHP server

我有一个连接到PHP服务器的android应用程序项目,该项目是在codeigniter中编写的。

我的JSONparser是:

package com.example.com.tourism;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

       // constructor
       public JSONParser() {

       }

       // function get json from url
       // by making HTTP POST or GET method
       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;

       }
    }

和我连接到服务器的活动Java代码是

package com.example.com.tourism;

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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SignUp extends Activity {

    EditText first,last,birth ,pass;
    private ProgressDialog pDialog;
    private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_SUCCESS = "success";
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sign_up);

            Button signUp=(Button)findViewById(R.id.sign_up);

            first =(EditText) findViewById(R.id.edfname);
            last =(EditText) findViewById(R.id.edlname);
            pass =(EditText) findViewById(R.id.edpass);
            signUp.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new Createnewuser().execute();
                }
            });

    }

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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SignUp.this);
            pDialog.setMessage("Creating User..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = first.getText().toString();
            String price = last.getText().toString();
            String description = pass.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("first_name", name));
            params.add(new BasicNameValuePair("last_name", price));
            params.add(new BasicNameValuePair("password", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_user,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

    }       
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }


    }

和日志猫中的错误是

07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514):    at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514):    ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames!  The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames!  The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames!  The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames!  The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames!  The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514):     at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514):     at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514):     at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514):     at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514):     at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514):     at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514):     at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514):     at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514):     at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514):     at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514):     at dalvik.system.NativeStart.main(Native Method)

我不知道问题出在哪里,请帮助我我的代码不正确吗??? 如果有人有正确的代码,请给我,我正在使用PHP的codeigniter,这是我在上面称呼的代码

function register_get()
    {
        $json = array('status' => false );
        if($this->input->post()==null){
            $this -> response($json, 200);
            }

        $firstname = $this->post("first_name");
        $lastname = $this->post("last_name");
        $password = $this->post("password");
        if(!$firstname || !$lastname || !$password){
            $json['status'] = "wrong insert";
            $this -> response($json, 200);
        }

        $this->load->model('Data_model');
        $result = $this->Data_model->search($firstname, $lastname);

        if($result)
        {
            $this->Data_model->insert($firstname,$lastname,$password);
            $json['status'] = true;

        }
        // here if false..
        $this -> response($json, 200);
    }

您的PHP存在问题。 您没有传回任何JSON。 您将需要更改脚本以将数组编码为JSON。

$result = json_encode($json)

返回实际的JSON将有所帮助。 确保您也不返回任何HTML。 您的Java尝试解析JSON响应,但是您正在使用<!DOCTYPE ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM