How to send a JSON object over Request with Android?

前端 未结 8 1994
慢半拍i
慢半拍i 2020-11-22 03:32

I want to send the following JSON text

{\"Email\":\"aaa@tbbb.com\",\"Password\":\"123456\"}

to a web service and read the response. I kno

8条回答
  •  离开以前
    2020-11-22 03:49

    HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

    public static String makeRequest(String uri, String json) {
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try {
            //Connect 
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
    
            //Write
            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();
    
            //Read
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
    
            String line = null;
            StringBuilder sb = new StringBuilder();
    
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
    
            bufferedReader.close();
            result = sb.toString();
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    

提交回复
热议问题