天天看點

Android進行Post送出JSON資料注意事項

剛好業務需要寫一個測試程式給客戶使用,直接入主題吧!

請求位址:http://12.32.12.32:91889/testx.php

請求參數:

{

    "test1": "顧家家居口味咯咯咯",

    "test2": "把1冊",

    "test3": "13512341234",

    "test4": "5rW35Y2X55uR54ux566h55CG5bGA6LCD5bqm5oyH5oyl5bmz5Y",

    "test5": "1234s"

}

使用postman工具直接請求成功,使用寫的程式就失敗,請關注下面demo程式的紅色标注部分!

try {

       JSONObject body = new JSONObject();

       body.put("test1", etText.getText().toString());

       body.put("test2", etName.getText().toString());

       body.put("test3", etPhone.getText().toString());

       body.put("test4", "5rW35Y2X55uR54ux566h55CG5bGA6LCD5bqm5oyH5oyl5bmz5Y");

       body.put("test5", "1234s");

       String urlPath = "http://12.32.12.32:91889/testx.php";

       URL url = new URL(urlPath);

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setConnectTimeout(5000);

       // 設定允許輸出

       conn.setDoOutput(true);

       conn.setDoInput(true);

       conn.setRequestMethod("POST");

       // 設定contentType

       conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

//               DataOutputStream os = new DataOutputStream( conn.getOutputStream(),"UTF-8");

       OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

       BufferedWriter bw = new BufferedWriter(osw);

       String content = String.valueOf(body);

       osw.write(content);

       osw.flush();

       osw.close();

       if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

           InputStreamReader in = new InputStreamReader(conn.getInputStream());

           BufferedReader bf = new BufferedReader(in);

           String recieveData = null;

           String result = "";

           while ((recieveData = bf.readLine()) != null) {

               result += recieveData + "\n";

           }

           in.close();

           conn.disconnect();

           if(result.contains("\"returnCode\":1")) {

               Message msg = new Message();

               msg.what = 1; // 成功

               mHandler.sendMessage(msg);

           }

       }

} catch (Exception io) {

       io.printStackTrace();

}

程式難度不大,遇到的一點小問題備注上。

PS:給客戶資料一定簡單易用,由于是接口示範程式,是以 我并沒有打算直接給接口讓客戶使用Postman等工具,而是讓其安裝到手機上,随時随地友善測試。程式解決的是客戶問題,而不是多高大上的技術!