摘要:Android 連接 Server (Android 部分)
Android 連接伺服器,個人覺得最好的方是 在伺服器寫 WebAPI
所以 Andoid 的部分就只要 HttpGet 就好了~
Web API 的部分可以參考微軟的官方教學
以下是我在 Server 端定期校訂時間,而 Android 這裡需要取得正確的時間
package huadi.EleInvAccounts.Inquiry;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.util.Log;
public class GetNTP extends AsyncTask
{
@Override
protected String doInBackground(String... params)
{
if (params.length < 0)
return null;
HttpGet get = new HttpGet("http://120.127.14.60/HuadiNTP/time/NowTime/?format=json");
String strResult = "";
String NowTime = "";
try
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
httpResponse = httpClient.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == 200)//判斷網路連接是否成功
{
strResult = EntityUtils.toString(httpResponse.getEntity()); //抓下來的資料
Log.e("strResult", strResult);
JSONArray jsonArray = new JSONArray(strResult); //{}為JSONObject []為JSONArray
NowTime = jsonArray.getJSONObject(0).getString("NowTime"); //ntp
//String DateTime = jsonArray.getJSONObject(0).getString("DateTime"); //yyyyMMdd ...
}
}
catch (Exception e)
{
Log.e("GetNTP", e.toString());
}
return NowTime;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(String... params)
{
super.onProgressUpdate(params);
}
}
話說貼程式碼的時候
我的 <> 裡面的三個 String 會變小寫
最後還幫我多加了一行....