Error parsing data org.json.JSONException:

Android环境是wampserver+eclipse,在网上找了个demo,想实现初步的注册和登录功能.但是测试的时候报了Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject,卡住了。求解...

logcat打印的信息:

 11-17 15:40:04.666: D/Log_Debug(14690): this json<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
11-17 15:40:04.666: D/Log_Debug(14690): <HTML><HEAD><TITLE>Bad Request</TITLE>
11-17 15:40:04.666: D/Log_Debug(14690): <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
11-17 15:40:04.666: D/Log_Debug(14690): <BODY><h2>Bad Request - Invalid Header</h2>
11-17 15:40:04.666: D/Log_Debug(14690): <hr><p>HTTP Error 400. The request has an invalid header name.</p>
11-17 15:40:04.666: D/Log_Debug(14690): </BODY></HTML>
11-17 15:40:04.669: E/JSON Parser(14690): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
11-17 15:40:04.671: W/System.err(14690): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference



2个回答

JSONParser.java

 package com.example.travelguide;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
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()
    {}

    public JSONObject makeHttpRequest(String url,String method,List<NameValuePair> params)
    {
        try{
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                //httpPost.setEntity(new UrlEncodedFormEntity(params));

                //httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置编码
                StringEntity se;
                se = new StringEntity(json.toString());
                httpPost.setEntity(se);
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));  


                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                //Log.e("Log_tag", "POST url is "+url.toString());
            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "gb2312");
                url += "?"+ paramString;
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                //Log.e("Log_tag", " GET url is"+url.toString());
            }
            else
            {
                Log.e("Log_tag", "Params Error");
            }
        } 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);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                sb.append(line + "\n");
               // Log.d("log_tag", "line is :"+line+sb.toString());
            }

            is.close();
            json = sb.toString();
//            Log.e("Log_tag", "this json is "+json.toString());
        } catch(Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            Log.d("json", json.toString());//李霜新加的

        }

        // try parse the string to a JSON object
        try{
            jObj = new JSONObject(json);

        } catch(JSONException e) {
            Log.d("Log_Debug", "this json"+json.toString());
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return  jObj;
    }



}
    /*static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

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

        // Making HTTP request
        try {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);// 建立HttpPost对象
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));// 设置编码

            // 发送Post,并返回一个HttpResponse对象
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();// Creates a new InputStream object of
                                            // the entity.

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

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-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());
            Log.d("json", json.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;

    }*/

唉我去,第一次提问没经验,重新贴代码

JSONParser.java

 package com.example.travelguide;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
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()
    {}

    public JSONObject makeHttpRequest(String url,String method,List<NameValuePair> params)
    {
        try{
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                //httpPost.setEntity(new UrlEncodedFormEntity(params));

                //httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置编码
                StringEntity se;
                se = new StringEntity(json.toString());
                httpPost.setEntity(se);
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));  


                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                //Log.e("Log_tag", "POST url is "+url.toString());
            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "gb2312");
                url += "?"+ paramString;
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                //Log.e("Log_tag", " GET url is"+url.toString());
            }
            else
            {
                Log.e("Log_tag", "Params Error");
            }
        } 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);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                sb.append(line + "\n");
               // Log.d("log_tag", "line is :"+line+sb.toString());
            }

            is.close();
            json = sb.toString();
//            Log.e("Log_tag", "this json is "+json.toString());
        } catch(Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            Log.d("json", json.toString());

        }

        // try parse the string to a JSON object
        try{
            jObj = new JSONObject(json);

        } catch(JSONException e) {
            Log.d("Log_Debug", "this json"+json.toString());
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return  jObj;
    }



}

registerAcyivity.java

 package com.example.travelguide;


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

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

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class registerActivity extends Activity {

    private EditText name, password, passText2, telText;
    private Button okBtn, resetBtn, cancelBtn;
    //private TextView nameView, passView1, passView2, telView;
    private int success;
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();

    private static String url = "http://192.168.139.1/register.php";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_SUCCESS = "success";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        okBtn = (Button) findViewById(R.id.okBtn);
        resetBtn = (Button) findViewById(R.id.resetBtn);
        cancelBtn = (Button) findViewById(R.id.cancelBtn);

        name = (EditText) findViewById(R.id.regnameText);
        password = (EditText) findViewById(R.id.passText1);
        passText2 = (EditText) findViewById(R.id.passText2);
        telText = (EditText) findViewById(R.id.telText);

//      nameView = (TextView) findViewById(R.id.regName);
//      passView1 = (TextView) findViewById(R.id.regPass1);
//      passView2 = (TextView) findViewById(R.id.regPass2);
//      telView = (TextView) findViewById(R.id.regTel);

        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // new

                // TODO Auto-generated method stub
                if (name.getText().toString().length() == 0) {
                    new AlertDialog.Builder(registerActivity.this)
                            .setTitle("错误!").setMessage("请输入姓名!")
                            .setPositiveButton("确定", null).show();
                    name.requestFocus();
                    password.setText("");
                    passText2.setText("");
                } else if (password.getText().toString().length() == 0) {
                    new AlertDialog.Builder(registerActivity.this)
                            .setTitle("错误!").setMessage("请输入新密码!")
                            .setPositiveButton("确定", null).show();
                    password.requestFocus();
                } else if (passText2.getText().toString().length() == 0) {
                    new AlertDialog.Builder(registerActivity.this)
                            .setTitle("错误!").setMessage("请确认密码!")
                            .setPositiveButton("确定", null).show();
                    passText2.requestFocus();
                }
                // else if(telText.getText().toString().length()==0){
                // new
                // AlertDialog.Builder(registerActivity.this).setTitle("错误!")
                // .setMessage("请输入手机号!").setPositiveButton("确定", null).show();
                // telText.requestFocus();
                // }
                else if (!password.getText().toString()
                        .equals(passText2.getText().toString())) {
                    new AlertDialog.Builder(registerActivity.this)
                            .setTitle("错误!").setMessage("两次密码输入不一致!")
                            .setPositiveButton("确定", null).show();
                    password.setText("");
                    passText2.setText("");
                    password.requestFocus();
                } else {

                    new Up().execute();
                    //name.requestFocus();
                }

            }
        });

        resetBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                name.setText("");
                password.setText("");
                passText2.setText("");
                telText.setText("");
                name.requestFocus();
            }
        });

        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

    class Up extends AsyncTask<String, String, String> {
        // 这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,在这里显示进度对话框
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(registerActivity.this);
            pDialog.setMessage("正在提交..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        // 后台执行
        protected String doInBackground(String... args) {
            String name1 = name.getText().toString();
            String password1 = password.getText().toString();
            String tel = telText.getText().toString();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name1));// 添加参数
            params.add(new BasicNameValuePair("password", password1));
            params.add(new BasicNameValuePair("tel", tel));


            try {
                JSONObject json = jsonParser.makeHttpRequest(url, "POST",params);
                String message =json.getString(TAG_MESSAGE);
                success=json.getInt(TAG_SUCCESS);

                //返回结果传递给onPostExecute();
                return message;
                //return "oops";
            } catch (Exception e) {
                e.printStackTrace();

                return "";
            }
        }

        /*
         * 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。
         * 此方法在主线程执行,任务执行的结果作为此方法的参数返回
         * 完成后台任务,当后台计算结束后调用。后台计算的结果会被作为参数传递给这一函数。
         */
        protected void onPostExecute(String message) {
            if(success==1){
                finish();
            }           
            if(success==0){
                String c="success is "+success;             
                password.setText("");               
                passText2.setText("");                              
                telText.setText("");
                name.requestFocus();    
            }           
            pDialog.dismiss();
            // message 为接收doInbackground的返回值
            Toast.makeText(getApplicationContext(), message, 8000).show();
        }
    }

    public static final String removeBOM(String json) {  

        if (json!=null && json.startsWith("\ufeff")) {  
                return json.substring(1);  
        } else {  
                return json;  
        }  
}



}

register.php

 <?php
/*
 * Created on 2015-4-24
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 // array for JSON response
//var_dump(json_decode($json));


$response = array();
include("conn.php");
$json = file_get_contents ( 'php://input' );
$obj = json_decode ( $json );
var_dump(json_decode($json));

    if (isset($_POST['name']) && isset($_POST['password']) ) {
    $name = $_POST['name'];
    $password = $_POST['password'];
    $tel=$_POST['tel'];

    $sql="SELECT * FROM user WHERE name='$name'";
    $res=mysql_query($sql);
    $row = mysql_fetch_array($res, MYSQL_ASSOC);
    if(!mysql_num_rows($res))
    {
        $result = mysql_query("INSERT INTO user(name,password,tel) VALUES('$name', MD5('$password'),'$tel')");
        if ($result) {
            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = urlencode('用户创建成功!');
            // echoing JSON response
            echo urldecode(json_encode($response));
        } else {
            // failed to insert row
            $response["success"] = 0;
            $response["message"] = urlencode('创建失败!');

            // echoing JSON response
            echo urldeode(json_encode($response));
        }
    }
    else{
            // failed to register
            $response["success"] = 0;
            $response["message"] = urlencode('用户已经存在!');
            // echoing JSON response
            echo urldecode(json_encode($response));

        }

}
else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = urlencode('请求失败!');

    // echoing JSON response
    echo urldecode(json_encode($response));

}

?>

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问