Android - HttpURLConnection POST Json

Android - HttpURLConnection POST Json

參考

http://blog.csdn.net/jia20003/article/details/50457453

因為API需要使用JSON傳值,導致原本的http post一直失效。

用原本的 AQuery也失效,當為空白時的參數,會自動消失,感覺就像沒傳一樣。

只好又客製化一個post function

跟原本的http post的差異在

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

            OutputStream os = conn.getOutputStream();
            DataOutputStream writer = new DataOutputStream(os);
            String jsonString = getJSONString(params);
            writer.writeBytes(jsonString);

而JSONString不需要在URLEncode(網路某個解用URLEncode一直試不成功)

這樣總結果如下


    public static String httpConnectionPost(String apiUrl,Map<String, String> params) {
        HttpURLConnection conn = null;
        StringBuilder response = new StringBuilder();

        try {
            URL url = new URL(apiUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setDoInput(true); //允許輸入流,即允許下載
            conn.setDoOutput(true); //允許輸出流,即允許上傳
            conn.setUseCaches(false); //設置是否使用緩存

            OutputStream os = conn.getOutputStream();
            DataOutputStream writer = new DataOutputStream(os);
            String jsonString = getJSONString(params);
            writer.writeBytes(jsonString);
            writer.flush();
            writer.close();
            os.close();
            //Get Response
            InputStream is = conn.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            reader.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            if(conn!=null) {
                conn.disconnect();
            }
        }

        return response.toString();
    }

    public static String getJSONString(Map<String, String> params){
        JSONObject json = new JSONObject();
        for(String key:params.keySet()) {
            try {
                json.put(key, params.get(key));
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return json.toString();
    }