Matin Hajatdoost
Matin Hajatdoost

Reputation: 83

Get Http Response headers and Request headers in Android

I post a query-string to a url and now I wanna get request headers and use one of its keys. I wrote a code that can get response headers but not the request header. Here's my code so far:

URL url = null;
        try {
            url = new URL(getString(R.string.auth_url));
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(10000);
            con.setConnectTimeout(15000);
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            String urlParameters  = "username="+ URLEncoder.encode(params[0], "UTF-8")+"&password="+URLEncoder.encode(params[1], "UTF-8")+"&captcha=1234";
            con.setRequestProperty( "charset", "utf-8");
            OutputStream os = con.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(urlParameters);
            writer.flush();
            writer.close();
            os.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            Log.i("body", "input = " + stringBuilder.toString());
            reader.close();

            return con.getHeaderFields().toString();

            } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;

The line return con.getHeaderFields().toString() gave me the whole response header. Now How should I change this code to get request header instead?!

hint: I used AsyncTask<> and the above lines are in my doInBackground method.

Upvotes: 0

Views: 3777

Answers (1)

IrM
IrM

Reputation: 41

Try to use:

1) getRequestProperties() API to receive all request header list

2) getRequestProperty(String field) API to receive the corresponding header by field name.

Upvotes: 1

Related Questions