2016-05-12 124 views
2

我正试图在Android中开发一个简单的客户端 - 服务器应用程序。从PHP代码获取响应时出现问题。它返回一个HTML代码而不是JSON。这是我用过的WAMP服务器的问题吗?HTTP发布请求返回HTML代码而不是JSON数据

这里是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; 
    } 
} 
+0

与您的Web开发人员讨论相同的使用邮递员工具来验证服务 –

+0

您可以在此处发布您在HTML代码中看到的内容吗? – Suyog

+0

最好是通过终端控制台上'curl -D - www.example.com'的原始数据。 –

回答

2

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

1

die(json_encode($response))变化呼应json_encode($response)

+0

谢谢你,但我已经尝试过这个。它没有改变我的错误.. –

+1

那么你为什么接受这个答案是正确的?很混乱。 – greenapps

+0

@greenapps对不起,我是这个网站的新手:) :) –

相关问题