gpt4 book ai didi

php - Android 将 JSON 发布到 Web 服务 php 并从服务接收 JSON

转载 作者:行者123 更新时间:2023-11-29 18:03:38 25 4
gpt4 key购买 nike

我试图通过将 JSON 发送到我在 PHP 中拥有的 Web 服务来在 Android 中编写登录服务,然后返回在 Web 服务 JSON 中处理过的服务。我的问题是发送 JSON,然后在 android 应用程序中读取 JSON。我已经找到了使用 ASyncTask 在应用程序中进行基本发布的方法,但我不确定从那里去哪里,我一直在对此进行大量搜索,但我现在有点困惑。非常感谢任何帮助!

这是我的 .java 文件

package com.example.logintest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
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 {

private static final String APP_TAG = "demo";
public static EditText txtUserName;
public static EditText txtPassword;
Button btnLogin;
Button btnCancel;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {


public void onClick(View v) {
// TODO Auto-generated method stub
new loginTask().execute();
/*if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(MainActivity.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(MainActivity.this, "Invalid Login",Toast.LENGTH_LONG).show();
}*/

}
});
}

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}


public static String postHttpResponse(URI absolute) {
Log.d(APP_TAG, "Going to make a post request");
StringBuilder response = new StringBuilder();
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try {
HttpPost post = new HttpPost();
post.setURI(absolute);
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", "login"));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(params));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
Log.d(APP_TAG, "HTTP POST succeeded");
HttpEntity messageEntity = httpResponse.getEntity();
InputStream is = messageEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
} else {
Log.e(APP_TAG, "HTTP POST status code is not 200");
}
} catch (Exception e) {
Log.e(APP_TAG, e.getMessage());
}
Log.d(APP_TAG, "Done with HTTP posting");
return response.toString();
}

class loginTask extends AsyncTask<Object, Object, String> {

//check if server is online
protected String doInBackground(Object... arg0) {
URI absolute = null;
try {
absolute = new URI("http://10.0.2.2/service/");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return postHttpResponse(absolute);
}

//set status bar to offline if flag is false
protected void onPostExecute(String xml) {
//XMLfromString(xml);
}

}

}

最佳答案

您可以将用户名和密码作为 jsonobject 发送到服务器:

//your code here....
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);

HttpPost post = new HttpPost();
post.setURI(absolute);
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", "login"));
params.add(new BasicNameValuePair("loginjson",json.toString()));
post.setEntity(new UrlEncodedFormEntity(params));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
//your code here....

在服务器端从 loginjson queryString 检索 json 对象。

为了以 json 格式从服务器返回结果,您需要在 AsyncTask 的 onPostExecute 方法中将返回的字符串从服务器转换为 JsonObject ir JsonArray 为:

protected void onPostExecute(String jsonstring) {
// if server returning jsonobject
JSONObject jsonobj=new JSONObject(jsonstring);
// get values from jsonobject

// if server returning jsonArray
JSONArray jsonarray=new JSONArray(jsonstring);
// get values from JSONArray

}

关于php - Android 将 JSON 发布到 Web 服务 php 并从服务接收 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492040/

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