Android+PHP は HttpClient を使用して POST リクエストを送信し、JSON を使用して応答を解析します。
ここでは、Android プログラムにネットワーク機能を持たせる方法を紹介します。もちろん、最初にサーバーを用意する必要があります。テストするだけの場合は、代わりに LAN (コンピューターの Wi-Fi に接続された携帯電話) を使用できます。
コンピューターがApache+PHP環境で構成されている必要があります。
以下は簡単な Android プログラムです。Java の基礎があれば、その意味を大まかに「推測」できると思います。 (プログラムが十分に書かれていない可能性があります)
Androidプログラム
レイアウトファイル
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/<strong>Activity</strong>_vertical_margin" android:paddingleft="@dimen/<strong>Activity</strong>_horizontal_margin" android:paddingright="@dimen/<strong>Activity</strong>_horizontal_margin" android:paddingtop="@dimen/<strong>Activity</strong>_vertical_margin" tools:c android:orientation="vertical"> <textview android:layout_width="match_parent" android:layout_height="wrap_content" android:>gravity="center" android:text="使用JSON解析" android:textSize="30sp"/> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:>gravity="center"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="账号" android:textsize="20sp" android:layout_marginright="20dp"></textview> <edittext android:id="@+id/et_id" android:layout_width="match_parent" android:layout_height="wrap_content"></edittext> </linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:>gravity="center"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码" android:textsize="20sp" android:layout_marginright="20dp"></textview> <edittext android:id="@+id/et_psw" android:layout_width="match_parent" android:layout_height="wrap_content"></edittext> </linearlayout> <button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="登录"></button> </textview></linearlayout>MainActivity.java
package com.example.jsontest; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.<strong>Apache</strong>.http.HttpEntity; import org.<strong>Apache</strong>.http.HttpResponse; import org.<strong>Apache</strong>.http.NameValuePair; import org.<strong>Apache</strong>.http.client.HttpClient; import org.<strong>Apache</strong>.http.client.entity.UrlEncodedFormEntity; import org.<strong>Apache</strong>.http.client.methods.HttpPost; import org.<strong>Apache</strong>.http.impl.client.DefaultHttpClient; import org.<strong>Apache</strong>.http.message.BasicNameValuePair; import org.<strong>Apache</strong>.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONObject; import android.os.Bundle; import android.os.Looper; import android.support.v7.app.ActionBar<strong>Activity</strong>; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Main<strong>Activity</strong> extends ActionBar<strong>Activity</strong> { EditText et_id; EditText et_psw; Button btn_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.<strong>Activity</strong>_main); initView(); } private boolean check(String id, String psw) { if("".equals(id) || "".equals(psw)) return false; return true; } private void initView() { et_id = (EditText)findViewById(R.id.et_id); et_psw = (EditText)findViewById(R.id.et_psw); btn_login = (Button)findViewById(R.id.btn_login); btn_login.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //获取用户输入的用户名和密码 final String id = et_id.getText().toString().trim(); final String psw = et_psw.getText().toString().trim(); if(check(id, psw)) { new Thread() { public void run() { try { HttpPost post = new HttpPost("这里要改成服务器文件所在URL地址"); //如果传递参数个数比较多,可以对传递的参数进行封装 List<namevaluepair> params = new ArrayList<namevaluepair>(); params.add(new BasicNameValuePair("id", id)); params.add(new BasicNameValuePair("psw", psw)); //设置请求参数 post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpClient httpClient = new DefaultHttpClient(); //发送POST请求 HttpResponse response = httpClient.execute(post); //如果服务器成功地返回响应 if(response.getStatusLine().getStatusCode() == 200) { //String msg = EntityUtils.toString(response.getEntity()); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响 String line = "0"; while((line = reader.readLine()) != null) { sb.append(line + "\n"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响 } is.close(); //获取请求响应结果 String result = sb.toString(); System.out.println(result); //打包成JSON进行解析 JSONArray jsonArray = new JSONArray(result); JSONObject jsonData = null; //返回用户ID,用户密码 String userId = ""; String userPsw = ""; //使用List进行存储 List<string> data = new ArrayList<string>(); for(int i = 0; i 索引,根据<strong>索引</strong>获取值 userPsw = jsonData.getString("userPsw"); //userPsw是来源于服务器端php程序响应结果res的<strong>索引</strong>,根据<strong>索引</strong>获取值 data.add("用户ID:" + userId + ",用户密码:" + userPsw); //保存返回的值,可进行相应的操作,这里只进行显示 } Looper.prepare(); Toast.makeText(Main<strong>Activity</strong>.this, data.toString(), Toast.LENGTH_LONG).show(); Looper.loop(); } else { Looper.prepare(); Toast.makeText(Main<strong>Activity</strong>.this, "登录失败", Toast.LENGTH_LONG).show(); Looper.loop(); } } catch(<strong>Exception</strong> e) { e.printStackTrace(); } } }.start(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent <strong>Activity</strong> in <strong>AndroidManifest.xml</strong>. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </string></string></namevaluepair></namevaluepair>
そして、以下はサーバーサイドのphpファイルです(ファイル内でデータベースに接続していない操作については、必要に応じてデータベースに接続して動的データを取得することができます。PHPを知っている人は、これを簡単にデータベースに接続して取得するように変更できますデータ)
checkId.php
<?php //获取客户端发送过来的ID和密码 $id=$_POST['id']; $psw=$_POST['psw']; if($id == "admin" && $psw == "123") { $res=array(array()); $res[0]['userId']=$id; $res[0]['userPsw']=$psw; $res[1]['userId']="testId1"; $res[1]['userPsw']="testPsw1"; $res[2]['userId']="testId2"; $res[2]['userPsw']="testPsw2"; } echo json_encode($res); ?>
上記では、HttpClient を使用して POST リクエストを送信し、JSON を使用して応答を解析する方法 (重力、Apache、例外、インデックス、データベース接続など) を紹介しました。PHP チュートリアルに興味のある友人に役立つことを願っています。

PHPSESSIONの障害の理由には、構成エラー、Cookieの問題、セッションの有効期限が含まれます。 1。構成エラー:正しいセッションをチェックして設定します。save_path。 2.Cookieの問題:Cookieが正しく設定されていることを確認してください。 3.セッションの有効期限:セッションを調整してください。GC_MAXLIFETIME値はセッション時間を延長します。

PHPでセッションの問題をデバッグする方法は次のとおりです。1。セッションが正しく開始されるかどうかを確認します。 2.セッションIDの配信を確認します。 3.セッションデータのストレージと読み取りを確認します。 4.サーバーの構成を確認します。セッションIDとデータを出力し、セッションファイルのコンテンツを表示するなど、セッション関連の問題を効果的に診断して解決できます。

session_start()への複数の呼び出しにより、警告メッセージと可能なデータ上書きが行われます。 1)PHPは警告を発し、セッションが開始されたことを促します。 2)セッションデータの予期しない上書きを引き起こす可能性があります。 3)session_status()を使用してセッションステータスを確認して、繰り返しの呼び出しを避けます。

PHPでのセッションライフサイクルの構成は、session.gc_maxlifetimeとsession.cookie_lifetimeを設定することで達成できます。 1)session.gc_maxlifetimeサーバー側のセッションデータのサバイバル時間を制御します。 0に設定すると、ブラウザが閉じているとCookieが期限切れになります。

データベースストレージセッションを使用することの主な利点には、持続性、スケーラビリティ、セキュリティが含まれます。 1。永続性:サーバーが再起動しても、セッションデータは変更されないままになります。 2。スケーラビリティ:分散システムに適用され、セッションデータが複数のサーバー間で同期されるようにします。 3。セキュリティ:データベースは、機密情報を保護するための暗号化されたストレージを提供します。

PHPでのカスタムセッション処理の実装は、SessionHandlerInterfaceインターフェイスを実装することで実行できます。具体的な手順には、次のものが含まれます。1)CussentsessionHandlerなどのSessionHandlerInterfaceを実装するクラスの作成。 2)セッションデータのライフサイクルとストレージ方法を定義するためのインターフェイス(オープン、クローズ、読み取り、書き込み、破壊、GCなど)の書き換え方法。 3)PHPスクリプトでカスタムセッションプロセッサを登録し、セッションを開始します。これにより、データをMySQLやRedisなどのメディアに保存して、パフォーマンス、セキュリティ、スケーラビリティを改善できます。

SessionIDは、ユーザーセッションのステータスを追跡するためにWebアプリケーションで使用されるメカニズムです。 1.ユーザーとサーバー間の複数のインタラクション中にユーザーのID情報を維持するために使用されるランダムに生成された文字列です。 2。サーバーは、ユーザーの複数のリクエストでこれらの要求を識別および関連付けるのに役立つCookieまたはURLパラメーターを介してクライアントに生成および送信します。 3.生成は通常、ランダムアルゴリズムを使用して、一意性と予測不可能性を確保します。 4.実際の開発では、Redisなどのメモリ内データベースを使用してセッションデータを保存してパフォーマンスとセキュリティを改善できます。

APIなどのステートレス環境でのセッションの管理は、JWTまたはCookieを使用して達成できます。 1。JWTは、無国籍とスケーラビリティに適していますが、ビッグデータに関してはサイズが大きいです。 2.cookiesはより伝統的で実装が簡単ですが、セキュリティを確保するために慎重に構成する必要があります。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ホットトピック









