我想用 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 ();