開發Android時,如何用Post的方式 Call API來取得值
首先 ```csharp
String UrlLocation = 你的API位置; //API位置String PostData = 要傳遞的資料(字串); //EX: ID=Toyo&Name=Steven HttpURLConnection conn = null; StringBuilder sb = new StringBuilder(); try { URL Url = new URL(UrlLocation); conn = (HttpURLConnection)Url.openConnection(); conn.setRequestMethod("POST"); //要呼意的方式 Get Or Post conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); //開始傳輸資料過去給API OutputStream Output = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(Output, "UTF-8")); writer.write(PostData); writer.flush(); writer.close(); Output.close(); //讀取API回傳的值 BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream(),"utf-8")); String line; while ((line=br.readLine())!=null) { sb.append(line); } } catch(Exception ex) { Log.e("API_Post",ex.getMessage()); } finally { if (conn != null) conn.disconnect(); } return sb.toString();
1 |
|
- 最後,因為在Debug模式AsyncTask並不會進入,所以要在doInBackground的事件裡面加上這行,但因為非Debug模式下這行會造成Android沒有回應, 所以記得在部署時把這行拿掉!! ```csharp
android.os.Debug.waitForDebugger();
1 |
|