dongwupu5991 2014-12-02 11:28
浏览 81

将JSON对象解析为Restful Web服务

I am developing an android registration system that communicates with a mysql database through JSON. The restful web service was written with PHP and Slim library. i have tested the web service using Advanced Rest Client App by parsing a json payload data into it and it works perfectly fine with the result shown below. At the moment i am trying to parse user data from the android app to the server and it shows this error (Error parsing data org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject). I would someone to tell me what i am doing wrong coz i feel the error is from my JSONParser class and Userfunction. Thanks in advance.

Here is my test result

{"tag":"signup","success":1,"error":0,"uid":"547d92b0480711.90973742",
"result":{"firstname":"mish","lastname":"harry","email":"mishael19@gmail.com"}}

Here is JSONParser

public class JSONParser2 {

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

// constructor
public JSONParser2() {
}

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params){

    try{
        if(method.equals("POST")){
            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"){
            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 + "
");
        }
        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;    
}
}

here is my Userfunction

public class UserFunctions {

private JSONParser2 jsonParser2;

private static String signupURL = "http://globalpadtutorials.globalpad.info/loginSignup/v1/signup";

private static String signup_tag = "signup";

private static String postMethod = "POST";

public UserFunctions(){
    jsonParser2 = new JSONParser2();
}

public JSONObject signupUser(String fname, String lname, String email, String pwd){

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", signup_tag));
    params.add(new BasicNameValuePair("firstname", fname));
    params.add(new BasicNameValuePair("lastname", lname));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", pwd));

    JSONObject json = jsonParser2.makeHttpRequest(signupURL, postMethod, params);
     Log.e("JSON", json.toString());
    return json;
}
}

Error stack

12-02 11:04:19.681: E/JSON Parser(10024): Error parsing data org.json.JSONException: Value <html>   
<head><title>Slim of type java.lang.String cannot be converted to JSONObject

PHP code

function createUser(){

$request = \Slim\Slim::getInstance()->request();
$resp = \Slim\Slim::getInstance()->response();
$resp['Content-Type'] = 'application/json; charset=utf-8';
$body = $request->getBody();
$users = json_decode($body);
$dbhandler = new DbHandler();
$tag = $users->tag;
$fname = $users->firstname;
$lname = $users->lastname;
$email = $users->email;
$pwd = $users->password;

$response = array("tag" => $tag, "success" => 0, "error" => 0);

if($tag == 'signup') {
    if ($dbhandler->userExisted($email)) {
        $response["error"] = 2;
        $response["error_msg"] = "User already existed";
        echo json_encode($response);
    } else {
        $result = $dbhandler->addUser($fname, $lname, $email, $pwd);
        if ($result != false) {
            $response["success"] = 1;
            var_dump($result);
            $response["uid"] = $result["user_id"];
            $response["result"]["firstname"] = $result["firstname"];
            $response["result"]["lastname"] = $result["lastname"];
            $response["result"]["email"] = $result["email"];
            echo json_encode($response);
        } else {
            $response["error"] = 1;
            $response["error_msg"] = "An error occured during sign up";
            echo json_encode($response);
        }
    }
} else{
    $response["error"] = 1;
    $response["error_msg"] = "Invalid tag request: ".$tag;
    echo json_encode($response);
}
}

html error

Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}

Slim Application Error

The application could not run because of the following error:

Details

Type: ErrorExceptionCode: 8Message: Trying to get property of non-objectFile: /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.phpLine: 63

Trace

#0 /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php(63): Slim\Slim::handleErrors(8, 'Trying to get p...', '/home/globa390/...', 63, Array)
12-02 11:55:50.366: E/JSON(27492): #1 [internal function]: createUser()
12-02 11:55:50.366: E/JSON(27492): #2 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Route.php(462): call_user_func_array('createUser', Array)
12-02 11:55:50.366: E/JSON(27492): #3 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Slim.php(1326): Slim\Route->dispatch()
12-02 11:55:50.366: E/JSON(27492): #4 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/Flash.php(85): Slim\Slim->call()
12-02 11:55:50.366: E/JSON(27492): #5 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
12-02 11:55:50.366: E/JSON(27492): #6 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
12-02 11:55:50.366: E/JSON(27492): #7 /home/globa390/public_html/globalpadtutorials/loginSignup/library/Slim/Slim.php(1271): Slim\Middleware\PrettyExceptions->call()
12-02 11:55:50.366: E/JSON(27492): #8 /home/globa390/public_html/globalpadtutorials/loginSignup/v1/index.php(12): Slim\Slim->run()
12-02 11:55:50.366: E/JSON(27492): #9 {main}
  • 写回答

3条回答 默认 最新

  • dqn8235 2014-12-02 11:44
    关注

    Your url returns html page with 404 error. That's why you cant parse it as json.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组