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

java–HTTP post请求返回HTML代码而不是JSON数据,第1张

概述我正在尝试在Android中开发一个简单的客户端–服务器应用程序.从PHP代码获取响应时遇到问题.它返回HTML代码而不是JSON.这是我用过的WAMP服务器的问题吗?这是PHP代码:<?phpinclude_once'./connect_db.php';$db=newDBConnect();$response=array();$username=$_POST[

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

这是PHP代码:

<?PHPinclude_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;    }}

解决方法:

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

总结

以上是内存溢出为你收集整理的java – HTTP post请求返回HTML代码而不是JSON数据全部内容,希望文章能够帮你解决java – HTTP post请求返回HTML代码而不是JSON数据所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1111090.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存