【发布时间】:2016-04-18 10:35:08
【问题描述】:
有很多关于 JSONParser 的问题,但似乎没有任何效果。 所以,我在服务器上有一个 php 脚本。
这个 php 脚本从数据库中获取一些数据,并用这些数据生成一个 Json。
我验证了这个Json,它是正确的。
在 android 中,我有一个 JSONParser,它连接到 php 脚本 url 并获取网页内容。
问题是页面内容不正确,不知道为什么。
我还使用了 OkHttp 和 URLConnection,它给了我相同的输出。
我也使用了 RETROfit,但这也不起作用,我有一个关于 stackoverflow 的问题。
这可能与 JavaScript 相关...
这是脚本链接:
这是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 在 localhost 上运行此请求,我认为问题出在您的免费虚拟主机站点上。
-
它对我的一个朋友有用,但我不知道为什么它对我不起作用。我会尝试使用其他主机或 xampp
-
我使用邮递员向您的 php 文件发送请求,我得到了相同的结果。尝试发送一个少 cookie 的请求。
-
无论有没有 cookie,它都会给出相同的结果
-
你从 php 端使用的字符集是什么。这是同一个iso-8859-1
标签: php android json httprequest