在Android中获取Http Response标头和Request标头

时间:2016-09-01 11:09:26

标签: android http-post httprequest httpurlconnection request-headers

我将查询字符串发布到网址,现在我想获取请求标头并使用其中一个密钥。我写了一个代码,可以获取响应头但不是请求头。到目前为止,这是我的代码:

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;

行返回con.getHeaderFields()。toString() 给了我整个响应标题。现在我应该如何更改此代码以获取请求标题?!

提示:我使用了AsyncTask<>以上几行都在我的doInBackground方法中。

1 个答案:

答案 0 :(得分:0)

尝试使用:

1)getRequestProperties() API接收所有请求标头列表

2)getRequestProperty(String field) API通过字段名称接收相应的标头。