HTTP post请求返回HTML代码而不是JSON数据

时间:2016-05-12 06:13:21

标签: java php android json

我正在尝试在Android中开发一个简单的客户端 - 服务器应用程序。从PHP代码获取响应时遇到问题。它返回HTML代码而不是JSON。这是我使用的WAMP服务器的问题吗?

这是PHP代码:

<?php
include_once './connect_db.php';
$db = new DBConnect();
$response = array();

$username = $_POST["username"];
$password = $_POST["password"];

if (empty($_POST['username']) || empty($_POST['password'])) 
{ 
    $response["success"] = 0; 
    $response["message"] = "One or both of the fields are empty.";
    die(json_encode($response));
}
$query = " SELECT * FROM account WHERE username = '$username'and password='$password'";
$sql1 = mysql_query($query); 
$row = mysql_fetch_array($sql1); 
if (!empty($row))
{ 
    $response["success"] = 1; 
    $response["message"] = "You have been sucessfully login"; 
    die(json_encode($response)); 
}
else
{ 
    $response["success"] = 0; 
    $response["message"] = "invalid username or password ";
    die(json_encode($response));
} 
mysql_close();
?>

login.java

package com.example.rossh.register;

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.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class login extends AppCompatActivity implements OnClickListener {
    private EditText user, pass;
    private Button login;
    JSONObject jsonObject;
    String response;
    // Progress Dialog
    private ProgressDialog pDialog;
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        //setup buttons
        login = (Button) findViewById(R.id.btnlogin);

        //register listeners
        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btnlogin:
                String username = user.getText().toString();
                String password = pass.getText().toString();
                boolean cancel =false;
                View focusView = null;
                if(TextUtils.isEmpty(username))
                {
                    user.setError("This field is required!!");
                    cancel=true;
                    focusView=user;
                }
                if(TextUtils.isEmpty(password))
                {
                    pass.setError("This field is requird!!!");
                    cancel=true;
                    focusView=pass;
                }
                if(cancel)
                {
                    focusView.requestFocus();
                } else {
                    new AttemptLogin().execute(username, password);
                }
                break;

            default:
                break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            String username = args[0];
            String password = args[1];
                // Building Parameters
                final int success;
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JsonParser jsonParser = new JsonParser();

                jsonObject = jsonParser.makeHttpRequest(AppConfig.LOGIN_URL, "POST", params);
                if (jsonObject != null) {
                    try{
                        Log.d("Json data",">"+jsonObject);
                        success = jsonObject.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            response = jsonObject.getString(TAG_MESSAGE);
                        } else {
                            Log.d("Login Failure!", jsonObject.getString(TAG_MESSAGE));
                            response = jsonObject.getString(TAG_MESSAGE);
                        }
                    } catch(JSONException e) {
                        e.printStackTrace();
                    }
                }
                return response;
            }

            /**
             * After completing background task Dismiss the progress dialog
             **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
                if (file_url != null) {
                    Toast.makeText(login.this, "ok", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

jsonParser.java

package com.example.rossh.register;

import android.util.Log;
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.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.widget.Toast;

public class JsonParser {
    InputStream is = null;
    static String json = "";
    static JSONObject jObj = null;

    // constructor
    public JsonParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    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));
                httpPost.setHeader("Content-Type","application/json");

                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, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.d("String",">"+json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            JSONArray jsonarray = new JSONArray(json);
            jObj = jsonarray.getJSONObject(0);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

3 个答案:

答案 0 :(得分:3)

可能是由于HTML中的一个或多个错误,或者您的页面返回非文本对象。确保您的HTML网页在从浏览器运行时不会出错。

答案 1 :(得分:2)

首先,我建议你的PHP脚本在返回json时设置正确的内容类型,请参阅Returning JSON from a PHP Script。另请参阅Java HttpRequest JSON & Response Handling了解如何在java中执行JSON请求。

答案 2 :(得分:1)

尝试将(moment.duration(moment($scope.endDate).diff(moment($scope.startDate)))).asMonths() 更改为die(json_encode($response))