gpt4 book ai didi

php - 将 Android 中的 POST 数据发送到 PHP

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

我正在寻找一种将 POST 数据发送到 PHP 脚本并显示结果的方法。我想将 $username 的 POST 数据发送到 php。这是我的 php 文件:

<?php

...// connect

$username = $_POST['txtUsername'];// this data

$mysqli->query("SET NAMES 'utf8'");
$sql="SELECT * FROM $username";
$result=$mysqli->query($sql);
while($e=mysqli_fetch_assoc($result)){
$output[]=$e;
}

print(json_encode($output));
$mysqli->close();

?>

我的 Activity :
DataParser.class

public class DataParser extends AsyncTask<Void,Void,Integer>{

Context c;
ListView lv;
String jsonData;

ProgressDialog pd;
ArrayList<Spacecraft> spacecrafts = new ArrayList<>();

public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

pd= new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing..Please wait");
pd.show();
}

@Override
protected Integer doInBackground(Void... voids) {
return this.parseData();
}

@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);


pd.dismiss();
if (result==0){
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}
else {
CustomAdapter adapter = new CustomAdapter(c,spacecrafts);
lv.setAdapter(adapter);
}
}
private int parseData(){
try {
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;

spacecrafts.clear();
Spacecraft s=null;


for (int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
int id = jo.getInt("id");
String name =jo.getString("name");
String send =jo.getString("send");
String comment =jo.getString("comment");
String date =jo.getString("date");

s=new Spacecraft();
s.setId(id);
s.setName(name);
s.setSend(send);
s.setComment(comment);
s.setDate(date);

spacecrafts.add(s);
}


return 1;
} catch (JSONException e) {
e.printStackTrace();
}

return 0;
}}

主要 Activity :

public class MainActivity extends AppCompatActivity implements AsyncResponse {

String urlAddress="http://mysite/myphp.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ListView lv = (ListView) findViewById(R.id.lv) ;

Intent intent = getIntent();
final String username = intent.getStringExtra("location");

Downloader d = new Downloader(MainActivity.this,urlAddress,lv);
d.execute();

和 Downloader.class:

public class Downloader extends AsyncTask<Void,Void,String> {

Context c;
String urlAddress;
ListView lv;

ProgressDialog pd;
public Downloader(Context c, String urlAddress, ListView lv) {
this.c = c;
this.urlAddress = urlAddress;
this.lv = lv;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching...Please wait");
pd.show();
}

@Override
protected String doInBackground(Void... voids) {
return this.downloadData();
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);

pd.dismiss();

if(s==null){
Toast.makeText(c,"Unsuccessful,Null,returned",Toast.LENGTH_SHORT).show();
}
else {
DataParser parser = new DataParser(c,lv,s);
parser.execute();

}

}


private String downloadData(){
HttpURLConnection con = Connector.connect(urlAddress);
if (con==null){
return null;
}
InputStream is=null;
try {

is=new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));

String line = null;
StringBuffer response = new StringBuffer();

if (br!=null){
while ((line=br.readLine())!=null){
response.append(line+"\n");
}

br.close();
}
else {return null;}
return response.toString();

} catch (IOException e) {
e.printStackTrace();
}
finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return null;
}}

请帮帮我,谢谢!

最佳答案

根据您提供的代码,看起来您正在下载数据,但您似乎没有发布任何数据。

有几种方法可以通过 HTTP POST 发送数据。您可以尝试使用 Google IO Volley API ,它会为您处理很多网络调用的逻辑。

例如:

RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://myurl.com";
JsonRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(JSONObject response)
{
Log.d(TAG, response.toString());
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, error.toString());
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtUsername", "mUsername");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
queue.add(postRequest);

您也可以编写自己的 AsyncTask 来执行发布。这是一个例子:

public class PostRequestAsyncTask extends AsyncTask<Void, Void, String
{
Context context;
Map<String, String> postParams;

/**
* Overridden constructor
*/
public PostRequestAsyncTask(Context context, Map<String, String> postParams)
{
this.context = context;
this.postParams = new LinkedHashMap<String, String>(postParams);
}

/**
* Default constructor
*/
public PostRequestAsyncTask() {}

public byte[] generatePostData()
{
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> dParam : postParams.entrySet())
{
if (postData.length() != 0)
postData.append('&');
try {
postData.append(URLEncoder.encode(dParam.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(dParam.getValue()), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
byte[] postDataBytes = null;
try
{
postDataBytes = postData.toString().getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return postDataBytes;
}

@Override
protected String doInBackground(Void... params)
{
/* Set params */
byte[] postDataBytes = generatePostData();

/* Set headers and write */
URL url = null;
HttpURLConnection conn = null;
try
{
url = new URL("https://myurl.com");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
}
catch (MalformedURLException | IOException e)
{
e.printStackTrace();
}

/* Retrieve response */
Reader in = null;
String response = new String();
try
{
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
response = "";
for (int c = in.read(); c != -1; c = in.read())
{
response += (char) c;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return response;
}

@Override
protected void onPostExecute(String resp) {
super.onPostExecute(resp);
JSONObject jsonResponse = null;
try
{
jsonResponse = new JSONObject(resp);
//do something with your json response
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}

然后像这样执行你的 AsyncTask:

Map<String, String> postParams = new LinkedHashMap<>();
postParams.put("txtUserName", "mUsername");
new PostRequestAsyncTask(MyActivity.this, postParams).execute();

关于php - 将 Android 中的 POST 数据发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154766/

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