Skip to content Skip to sidebar Skip to footer

Android Httpurlconnection Send Post And Params Get Request

I need a little help with sending an HttpUrlConnection from my android application. Till now I was doing this with a basic Http Client. But the problem is that when I receive a big

Solution 1:

Here is the way you can use HttpURLConnecion to make a connection to a web server :

        System.setProperty("http.keepAlive", "false");
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000); // miliseconds
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        Log.d("", "Status : " + status);

        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.d("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }

        InputStream response = new BufferedInputStream(
                connection.getInputStream());

        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0 && stopThread) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            // buffer2 is you chunked response
        }
        connection.disconnect();
    } catch (FileNotFoundException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }

Post a Comment for "Android Httpurlconnection Send Post And Params Get Request"