commons-logging.jar  还有 commons-codec.jar 这两个包没有就报错咯

用的httpclient 4.0 beta2

 

 MainTest {
    public static void main(String[] args) {
        String url 
="apache httpclient 使用";
        HttpClient httpClient
=new DefaultHttpClient();
        
//httpClient.getParams().setParameter(HttpClientParams.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
        
        
//get 方式
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(
"Accept-Language","zh-cn");//  apache httpclient 使用apache httpclient 使用 等等
        try{
            HttpResponse response 
= httpClient.execute(httpget);
            HttpEntity entity 
= response.getEntity();
            String webcode 
= new String(EntityUtils.toString(response.getEntity()).getBytes("ISO-8859-1"),"UTF-8");//具体情况具体分析
            if(entity!=null){
                
try{
                    entity.consumeContent();
                }
catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
catch(Exception ex){
            ex.printStackTrace();
        }

        
//post方式
        HttpPost httppost = new HttpPost(url);
        httppost.setHeader(
"apache httpclient 使用","apache httpclient 使用");
        
//        NameValuePair[] nvps = new NameValuePair[] {
//                new BasicNameValuePair("apache httpclient 使用", "apache httpclient 使用"),
//                new BasicNameValuePair("apache httpclient 使用", "apache httpclient 使用") // apache httpclient 使用
//        };
//        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(
new BasicNameValuePair("apache httpclient 使用""apache httpclient 使用"));// apache httpclient 使用
        
        
try{
            httppost.setEntity(
new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
            HttpResponse response 
= httpClient.execute(httppost);
            HttpEntity entity 
= response.getEntity();
            String webcode 
= EntityUtils.toString(response.getEntity());
            
if(entity!=null){
                
try{
                    entity.consumeContent();
                }
catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

相关文章: