gpt4 book ai didi

php - Android/PHP - JSONParser 无法将网页内容作为 JsonObject 获取

转载 作者:行者123 更新时间:2023-11-30 01:24:01 25 4
gpt4 key购买 nike

有很多关于 JSONParser 的问题,但似乎没有任何效果。所以,我在服务器上有一个 php 脚本。

此 php 脚本从数据库中获取一些数据并使用此数据生成 Json。

我验证了这个 Json,它是正确的。

在 android 中,我有一个连接到 php 脚本 url 并获取网页内容的 JSONParser。

问题是页面内容不正确,不知道为什么。

我还使用了 OkHttpURLConnection,它给了我相同的输出。

我还使用了 RETROfit 但这也不起作用,我对 stackoverflow 有一个问题。

这可能与 JavaScript 相关...

这是脚本链接:

PHP script link

这是php脚本生成的json:

    {
"success": 0,
"message": "RequiredFieldMissing"
}

这是 PHP 脚本:

<?php 
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['param1']) && isset($_POST['param2'])){

// include db connect class
require_once __DIR__ . '/connect_to_db.php';

// connecting to db
$db = new DB_CONNECT();

$param1 = $_POST['param1'];
$param2 = $_POST['param2'];

// get data
$result = mysql_query("SELECT param1 FROM tableName WHERE param2 = '$param2'") or die(mysql_error());

if (mysql_num_rows($result)>0) {

$row = mysql_fetch_array($result);
if ($row["param1"] == $param1){
// success
$response["success"] = 1;
$response["message"] = "Correct";
} else {
// no success
$response["success"] = 0;
$response["message"] = "Incorrect";
}

} else {
// no data found
$response["success"] = 0;
$response["message"] = "NoData";

}
// echo JSON
echo json_encode($response);
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "RequiredFieldMissing";

// echoing JSON
echo json_encode($response);
}
?>

这是JSONParser:

    public class JSONParser {

static InputStream is = null;

static JSONObject jObj = null;

static String json = "";

// 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));

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, "iso-8859-1"), 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());
}

// 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;

}
}

这是build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
compileSdkVersion 23
buildToolsVersion "23.0.0"
useLibrary 'org.apache.http.legacy'

defaultConfig {
applicationId "com.myApp"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.0'
compile 'com.android.support:support-v4:23.0.0'
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile 'org.apache.commons:commons-lang3:3.4'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.google.code.gson:gson:2.4'
compile 'org.glassfish:javax.annotation:10.0-b28'
}

这是AsyncTask 类:

public class SomeTask extends AsyncTask<Void, Void, Boolean> {

private final String param1;

private final String param2;

private String message;

UserLoginTask(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
message = StringUtils.EMPTY;
}

@Override
protected Boolean doInBackground(Void... param) {

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "param1Value"));
params.add(new BasicNameValuePair("param2", "param2Value"));

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(my_url, "GET", params);

if (json == null) {
return Boolean.FALSE;
} else {
Log.d("JSON: ", json.toString());
}

try {
if (json.getInt(TAG_SUCCESS) == 1) {
return Boolean.TRUE;
} else {
message = json.getString(TAG_MESSAGE);
return Boolean.FALSE;
}
} catch (JSONException e) {
e.printStackTrace();
}

return Boolean.FALSE;
}

@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);

if (success) {
finish();
startActivity(new Intent(ThisActivity.this, NextActivity.class));
} else {
if ("Incorrect".equals(message)) {
mPasswordView.setError(getString(R.string.error_incorrect_credentials));
mPasswordView.requestFocus();
} else if ("NoData".equals(message)) {
mPasswordView.setError(getString(R.string.error_no_account_found));
mPasswordView.requestFocus();
} else {
mPasswordView.setError(getString(R.string.unknown_error));
mPasswordView.requestFocus();
}
}
}
}

这是我得到的输出:

<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("6edf9232af73be55d6cc499e851409b9");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; document.cookie="referrer="+escape(document.referrer); location.href="http://mobilehealth.byethost11.com/aScript.php?param1=param1Value&param2=param2Value&ckattempt=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>

LOGCAT:

E/JSON Parser: Error parsing data org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject

这里抛出:jObj = new JSONObject(json);

最佳答案

我不知道是什么问题,但我在 xampp 和不同的主机上试过,现在它可以工作了。我认为问题是主机以某种方式响应了 javascript。以上所有代码都是正确的。

关于php - Android/PHP - JSONParser 无法将网页内容作为 JsonObject 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36691522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com