0

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

客户端:

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
            }

网址连接:

 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 ();
4

1 回答 1

2

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

HttpPost 解决方案可能运行缓慢,因为您正在使用:

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

相反,这个STUPID 片段(在这种情况下逐字节读取实际上效率不高)使用:

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

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

于 2012-11-29T15:09:28.853 回答