- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的第一篇文章。我开始使用 Android。
我试图通过 mybringback 的教程将我的应用程序连接到网络服务,但我的 json 返回出现错误。
09-12 15:54:06.717: E/JSON Parser fallha(8254): Error parsing data org.json.JSONException: End of input at character 0 of
我已经找到了原因,这是因为它从我的 php 页面返回 HTML 而不是 json。当我尝试用我的 json 设置修复字符串时,它起作用了。
当我尝试从浏览器获取 json 时,它工作正常。
我在阅读器中设置了一个 Log.d,我得到了这个:
09-12 15:35:10.807: D/Acha Erro POR FAVOR(6691): <h1>Login</h1>
09-12 15:35:10.807: D/Acha Erro(6691): <form action="login.php" method="post">
09-12 15:35:10.807: D/Acha Erro(6691): Username:<br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="text" name="username" placeholder="username" />
09-12 15:35:10.807: D/Acha Erro(6691): <br /><br />
09-12 15:35:10.807: D/Acha Erro(6691): Password:<br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="password" name="password" placeholder="password" value="" />
09-12 15:35:10.807: D/Acha Erro(6691): <br /><br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="submit" value="Login" />
09-12 15:35:10.807: D/Acha Erro(6691): </form>
09-12 15:35:10.807: D/Acha Erro(6691): <a href="register.php">Register</a>
我花了大约 3 天时间试图找到解决该问题的方法。
在我的两个类和php之后
package com.example.testemysql;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
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.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
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 MainActivity extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.bazarsol.6te.net/ANDROID/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
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_main);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
//Intent i = new Intent(this, Register.class);
//startActivity(i);
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(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("URL",LOGIN_URL);
Log.d("PARAMETROS",""+ params);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Log.d("Login Successful!", "");
//Intent i = new Intent(Login.this, ReadComments.class);
finish();
//startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* 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(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSON解析器
package com.example.testemysql;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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();
Log.d("Acha o erro POR FAVOR ajuda",""+ httpResponse);
}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);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
Log.d("Acha Erro POR FAVOR",""+ reader.readLine());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("Acha Erro", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e);
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser fallha", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
PHP - 已更新
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
//gets user's info based off of a username.
$query = "
SELECT
indice,
usuario,
senha
FROM usuarios
WHERE
usuario = :username
";
$query_params = array(
':username' => $_POST["username"]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
print_r($_REQUEST);
print_r (var_dump($_POST));
print_r(get_headers());
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!2";
echo "Bruno 2";
die(json_encode($response&$ex));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST["password"] === $row["senha"]) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}?>
结果
09-16 16:58:00.687: D/Acha o erro POR FAVOR ajuda(29176):org.apache.http.message.BasicHttpResponse@42680990
09-16 16:58:00.687: D/Acha Erro POR FAVOR(29176): Array
09-16 16:58:00.687: D/Acha Erro(29176): (
09-16 16:58:00.687: D/Acha Erro(29176): )
09-16 16:58:00.687: D/Acha Erro(29176): array(0) {
09-16 16:58:00.687: D/Acha Erro(29176): }
09-16 16:58:00.687: D/Acha Erro(29176): {"success":0,"message":"Invalid Credentials!"}
最佳答案
在您的请求中,您应该指定所需的返回类型为 Json。
您可能需要在 HTTP 请求 header 中添加类似于以下内容的内容:
header('Content-Type: application/json');
在你的代码中,我会推荐这样的东西:
// 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();
关于php - Httppost 返回 html 而不是 Json 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815429/
我不明白为什么需要使用 [HttpPost("[action]")] 而不是 [HttpPost]? 如果使用[HttpPost("[action]")],那么来自角度客户端的请求会触发 Contro
我不明白为什么需要使用 [HttpPost("[action]")] 而不是 [HttpPost]? 如果使用[HttpPost("[action]")],那么来自角度客户端的请求会触发 Contro
所以我们有[HttpPost],这是一个可选属性。我知道这会限制调用,因此只能通过 HTTP POST 请求进行调用。我的问题是我为什么要这样做? 最佳答案 想象一下以下情况: [HttpGet] p
在 Scott Hanselman 的书中(第 1 章),他为我们提供了两个选项来实现 Create 操作方法的 [HttpPost]。 第一个依赖于 TryUpdateModel 根据传入的表单字段
我正在从 Android 应用程序向服务器发送 JSON 数据,我在人们添加的示例中看到: httpPost.setHeader("Content-type", "application/json")
- - - 更新 能够通过使用 UsernamePasswordCredentials 类来修复它 代码如下所示 val 客户端 = 新的 DefaultHttpClient client.getCr
这个问题让我很恼火。我正在重复使用适用于其他项目/类但不适用于我当前项目的相同代码。我所做的只是更改变量(POST 值和 EditText 名称)。但没有成功。 import java.util.Ar
这是我的代码: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
我正在为黑莓开发应用程序,我需要向我的服务器发送一个 Http 发布请求。我正在使用模拟器来测试我的应用程序,我发现这段代码是为了发送请求: http://vasudevkamath.techfiz.
我希望能够使用参数查看完整的 HttpClient/HttpPost URI。我不确定如何将其输出到我的控制台。 HttpClient httpclient = HttpClients.createD
我有一个带有 httpPost 属性的 ActionResult。如果我没有记错的话,当用户从 DateTimePicker 中选择日期时,我需要此属性。就我而言,我有 2 个日期时间选择器,类型为
嗨:)我遇到了一个简单的问题,但非常烦人。我正在尝试使用 HttpPost 类发送 http post 请求 这是返回InputStream的方法的一部分: HttpClient
我正在尝试通过 android studio 中的 java 将发布请求发送到我的 PHP 页面 首先我尝试了 httppost,但按下该键后应用程序崩溃了 然后我读到我必须使用新线程,我这样做了,但
我正在尝试将我的应用程序设置为在 HttpPost 上 3 秒后抛出超时异常。我正在从 ASyncTask 执行此请求。出于某种原因,即使我给它一个不存在的域,它也会挂起大约一两分钟,然后抛出最后一个
我正在尝试从 Android 应用程序中向我的 Google App Engine 应用程序发送 POST 请求,以便将文件上传到 blobstore 并将一些元数据上传到数据存储区。我构建了一个可以
在我的 CountryActivity.java 中,我有一个 HttpRequest 来检索维基百科的 json 信息。这是我使用 AsyncTask 的代码: private class D
我的 MainAcitivity 中有以下代码,用于使用方法 jsnrqstr.sendRequest(username, password, URL); 获取的用户名和密码登录到应用程序/p> lo
我有一个网页用 1 (true) 或 0 (false) 响应日志记录请求。当我尝试用另一个网页调用请愿书时,结果是正确的,它可以是 0 或 1。但是当我用 Android 应用程序调用它时,结果总是
在我的应用程序中,我必须从 4 个不同的 url 获取数据,然后在获取数据完成后,我必须按特定顺序显示项目。我正在使用 HttoPost 发送发布请求。我在不同的线程中分别发送 4 个请求。当线程获取
我尝试了所有可能的方法,但仍然出现以下错误 -1.无法解析符号ClientProtocolException2.无法解析符号HttpPost3.无法解析符号DefaultHttpClient JSON
我是一名优秀的程序员,十分优秀!