androidandroidhttpclient

How to get response after using POST method in Android


url is : http://localhost method type : post header : Content-Type:application/json, decode:2 data : xx

How can we achieve this in android??,and how do i get response from this ?? I saw that the Httpclient is deprecated

Any help would be appreciated


Solution

  • Try using HttpUrlConnection

    String Url, query;
    
        InputStream inputStream;
        HttpURLConnection urlConnection;
        byte[] outputBytes;
        String ResponseData;
        Context context;
    try{
                URL url = new URL(Url);
                urlConnection = (HttpURLConnection) url.openConnection();
                outputBytes = query.getBytes("UTF-8");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);
                urlConnection.setConnectTimeout(15000);
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.connect();
    
                OutputStream os = urlConnection.getOutputStream();
                os.write(outputBytes);
                os.flush();
                os.close();
    
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                ResponseData = convertStreamToString(inputStream);
    
        } catch (MalformedURLException e) {
    
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
    
                }
    
    
        public String convertStreamToString(InputStream is) {
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
    
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append((line + "\n"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }