我有一些非常奇怪的问题。因此,在我的应用程序中,当有人登录Google Plus时,名称,个人资料图片和ID将以JSON格式发送到网页,其中PHP脚本获取JSON并从中获取所有数据,检查数据库是否存在用户已存在,如果没有,则添加他。
所以我之前已经做过这个,为了一个不同的目的,现在当我试图复制我之前做的事情时,它不起作用。我不确定发生了什么,因为相同的代码适用于其他东西。
所以这是我的Android代码。我已经检查了日志以确保JSON对象具有所有内容。
public void updateData(String url, JSONObject jobj){
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 100000);
HttpPost httpPost = new HttpPost(url);
JSONArray sendJSON = new JSONArray();
sendJSON.put(jobj);
httpPost.setHeader("json", jobj.toString());
httpPost.getParams().setParameter("jsonpost", sendJSON);
try {
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
}
这是我的PHP代码:
<?php
require_once('connection.php');
if( isset($_SERVER['HTTP_JSON']) )
{
$data = json_decode($_SERVER['HTTP_JSON'], true);
$name = $data['name'];
$profilePicture = $data['profilePicture'];
$googleId = $data['googleId'];
//First see if the user is already in the database
$find_existing_query = "SELECT * FROM users WHERE googleId = $googleId";
$result = mysql_query($find_existing_query);
//Add user if there are no rows returned
if(mysql_num_rows($result) == 0)
{
$add_user_query = "INSERT INTO users (name, profilePicture, googleId) VALUES ($name, $profilePicture, $googleId)"
mysql_query($add_user_query);
}
$qry = "SELECT * FROM users";
$result = mysql_query($qry);
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
mysql_close();
}
else{
echo 'no JSON sent';
}
?>
另外,奇怪的是,当我访问网页时,我应该看到“没有发送JSON”,但我看到一个空白页面。并且没有放置在文件顶部的任何echo语句。此外,当我运行SELECT * FROM users查询时,它会从数据库中的其他表输出数据。
我真的不知道发生了什么。任何帮助将不胜感激!
答案 0 :(得分:1)
好的,这是使用WebServices执行此操作的一种优雅方式。
第1步: 创建一个可以安全处理AsynTask的泛型类。
public class WebServiceRestTask extends AsyncTask<HttpUriRequest, Void, Object> {
private static final String TAG = "WebServiceRestTask";
private AbstractHttpClient mClient;
private WeakReference<WebServiceRestCallback> mCallback;
private int ws_task;
public WebServiceRestTask(int ws_task) {
this(new DefaultHttpClient(), ws_task);
}
public WebServiceRestTask(AbstractHttpClient client, int task_number) {
mClient = client;
this.ws_task = task_number;
}
public interface WebServiceRestCallback {
public void onRequestSuccess(String response);
public void onRequestError(Exception error);
}
public void setResponseCallback(WebServiceRestCallback callback) {
mCallback = new WeakReference<WebServiceRestCallback>(callback);
}
@Override
protected Object doInBackground(HttpUriRequest... params) {
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response + ws_task;
} catch (Exception e) {
Log.w(TAG, e);
return e;
}
}
@Override
protected void onPostExecute(Object result) {
if (mCallback != null && mCallback.get() != null) {
if (result instanceof String) {
mCallback.get().onRequestSuccess((String) result);
} else if (result instanceof Exception) {
mCallback.get().onRequestError((Exception) result);
} else {
mCallback.get().onRequestError(
new IOException("Unknown Error Contacting Host"));
}
}
}
}
第2步: 创建一个将使用WebService类的方法。在这里,您将传递JSON,如下所示。
private void sendJSONTask(String uri, String jsonString,
int task_case) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("content-type", "application/json");
HttpEntity entity;
StringEntity s = new StringEntity(jsonString);
entity = s;
httpPost.setEntity(entity);
WebServiceRestTask task = new WebServiceRestTask(task_case);
task.setResponseDataCallback(LastActivity.this);
task.execute(httpPost);
Log.e("Sending JSON task : " + task_case,
jsonString);
} catch (Exception e) {
Log.e("ERROR sending JSON task: ", e.getMessage());
}
}
第3步 以这种方式调用您的任务。(参数task_number是唯一标识符,以防您有多种类型的JSON请求,并且您需要根据其ID来处理每个请求。)
sendJSONTask(uri_target, jsonData, 1);