为何setRequestMethod(“GET”)不生效

来源:互联网 发布:淘宝客应该怎么做 编辑:程序博客网 时间:2024/04/28 05:31
关键是你运行了这一句:httpurlconnection.setDoOutput(true); 就把请求改变为post请求了,请求头的输出并不需要通过httpurlconnection的输出流,只要设置就行,httpurlconnection会在你需要得到服务器响应的时候使用socket连接web服务器,将请求头输出到web服务器,所以这样写就可以了:
public static void doPost() {  
try {  
url = new URL("http://www.XXXX.com/blogs/list");  

httpurlconnection = (HttpURLConnection) url.openConnection();  
//httpurlconnection.setDoOutput(true); 这一句不要
//httpurlconnection.setRequestMethod("GET"); 这一句不要,缺省就是get
// httpurlconnection.getOutputStream().write(getFileString().getBytes());  

httpurlconnection.setRequestProperty("Cookie", "");  
httpurlconnection.setRequestProperty("Connection", "Keep-Alive");  
httpurlconnection.setRequestProperty("Referer", "http://extjs2.javaeye.com/");  
httpurlconnection.setRequestProperty("Host", "www.javaeye.com");  
//httpurlconnection.getOutputStream().flush(); 这一句不要
//httpurlconnection.getOutputStream().close(); 这一句不要

int code = httpurlconnection.getResponseCode();  
System.out.println(httpurlconnection.getContentEncoding());  
System.out.println(httpurlconnection.getContent());  
//System.out.println(httpurlconnection.getOutputStream());  
System.out.println("code " + code);  
} catch (Exception e) {  
e.printStackTrace();  
} finally {  
if (httpurlconnection != null)  
httpurlconnection.disconnect();  
}  setRequestMethod
原创粉丝点击