Send a JSON Object from Android to PHP server with POST method and HttpURLConnection

前端 未结 2 818
夕颜
夕颜 2020-12-03 02:30

I\'m trying to establish communication between my Android app and my WampServer on local network.

When I want to read data from the server, I have had success, but I

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 02:55

    Check with this code:

    public class UniversalNetworkConnection {
    
        public static String postJSONObject(String myurl, JSONObject parameters) {
            HttpURLConnection conn = null;
            try {
                StringBuffer response = null;
                URL url = new URL(myurl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                OutputStream out = new BufferedOutputStream(conn.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(parameters.toString());
                writer.close();
                out.close();
                int responseCode = conn.getResponseCode();
                System.out.println("responseCode" + responseCode);
                switch (responseCode) {
                    case 200:
                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String inputLine;
                        response = new StringBuffer();
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                        return response.toString();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.disconnect();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
            return null;
        }
    
    }
    

    on PHP Side:

    
    

提交回复
热议问题