URLConnection中的Referer不起作用

时间:2012-11-29 14:59:47

标签: android http httpclient httpurlconnection

我想用post方法获取一个html页面。首先我使用HttpClient,它没有给出正确的响应,然后我用Header添加Referer,它运行良好但速度太慢。所以我打算使用URLConnection,我还将Referer添加到Header,这次它没有返回我想要的内容。

的HttpClient:

httpclient = new DefaultHttpClient();  
            HttpPost httppost = new HttpPost(WhutGlobal.URL_HEADER_STR + "xscj_gc.aspx?xh=" + WhutGlobal.USER_ID + "&xm=" + WhutGlobal.USER_NAME + "&gnmkdm=N121605");
            try {
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httppost.setHeader("Referer", WhutGlobal.URL_HEADER_STR + "xscj_gc.aspx?xh=" + WhutGlobal.USER_ID + "&xm=" + WhutGlobal.USER_NAME + "&gnmkdm=N121605");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedInputStream bis = new BufferedInputStream(is);
                byte  bytearray[] = new  byte[800000];
                 int current= -1;
                 int i=0;  
                 while((current=bis.read())!=-1) {
                     bytearray[i] =(byte) current;
                      i++;
               }
              html = new String (bytearray,"GB2312");
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

的URLConnection:

 URL url = new URL(WhutGlobal.URL_HEADER_STR + "xscj_gc.aspx?xh=" + WhutGlobal.USER_ID + "&xm=" + WhutGlobal.USER_NAME + "&gnmkdm=N121605");
         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
         urlConnection.setDoOutput(true);
         urlConnection.setDoInput(true);
         urlConnection.setRequestMethod("POST");
         urlConnection.setRequestProperty("Connection", "Keep-Alive");
         urlConnection.setRequestProperty("Accept-Encoding", "gzip");
         urlConnection.setRequestProperty("Referer", WhutGlobal.URL_HEADER_STR + "xscj_gc.aspx?xh=" + WhutGlobal.USER_ID + "&xm=" + WhutGlobal.USER_NAME + "&gnmkdm=N121605");
         DataOutputStream wr = new DataOutputStream (
                   urlConnection.getOutputStream ());
         wr.writeBytes (urlParameters);
         wr.flush ();
         wr.close ();

1 个答案:

答案 0 :(得分:2)

获取html的HttpClientURLConnection方法之间的速度应该没有显着差异...它可以取决于连接速度(3G / Wifi)但是

HttpPost解决方案可能因为您正在使用而工作缓慢:

while((current=bis.read())!=-1) ...

而是 STUPID snipet (在这种情况下逐字节读取真的不高效)使用:

html = EntityUtils.toString(entity, "GB2312")

关于HttpURLConnection ...它实际上取决于你在urlParameters中发送的内容......在这种情况下你不应该使用DataOutputStream