HttpClient 学习记录


  HttpClient 是 Apache提供的一个HTTP连接工具包

  网址:http://hc.apache.org/

  4.5jar包下载:httpclient 4.5

  4.5src包下载:httpclient 4.5-src


    /*基本的get请求*/
    public final static void basicGet() throws ClientProtocolException, IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://www.weather.com.cn/data/sk/101010100.html");
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
            	StatusLine statusLine = response.getStatusLine();
            	System.out.println(statusLine);
            	
            	HttpEntity resEntity = response.getEntity();
            	InputStream content = resEntity.getContent();
            	InputStreamReader reader = new InputStreamReader(content);
            	BufferedReader bufferedReader = new BufferedReader(reader);
            	String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                }
                //调用中止请求对象
                httpget.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    
    /*基本的Post请求*/
    public final static void basicPost() throws ClientProtocolException, IOException{
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	try {
    		HttpPost httppost = new HttpPost("http://www.apache.org/");
    		CloseableHttpResponse response = httpclient.execute(httppost);
    		try {
    			StatusLine statusLine = response.getStatusLine();
    			System.out.println(statusLine);
    			
    			HttpEntity resEntity = response.getEntity();
    			InputStream content = resEntity.getContent();
    			InputStreamReader reader = new InputStreamReader(content);
    			BufferedReader bufferedReader = new BufferedReader(reader);
    			String lineTxt = null;
    			while((lineTxt = bufferedReader.readLine()) != null){
    				System.out.println(lineTxt);
    			}
    			
    			//调用中止请求对象
    			httppost.abort();
    		} finally {
    			response.close();
    		}
    	} finally {
    		httpclient.close();
    	}
    }
    
    /*带参数的Post请求*/
    public final static void parameterPost() throws IOException{
    	CloseableHttpClient httpClient = HttpClients.createDefault();
    	try {
    		HttpPost httpPost = new HttpPost("http://www.imooc.com/user/login");
    		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    		nvps.add(new BasicNameValuePair("username", "u"));
    		nvps.add(new BasicNameValuePair("password", "p"));
    		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    		CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				System.out.println(response.getStatusLine());
				System.out.println("Response content: " + EntityUtils.toString(response.getEntity(), "UTF-8")); 
				//调用中止请求对象
				httpPost.abort();
			}finally{
				response.close();
			}
		}finally{
			httpClient.close();
		}
    }
    
    /* 上传文件
     * 示例:ClientMultipartFormPost.java
     * */
    public final static void upload() throws IOException{
    	CloseableHttpClient httpClient = HttpClients.createDefault();
    	try{
    		HttpPost httpPost = new HttpPost("http://image.baidu.com/pictureup/uploadshitu?fr=flash&fm=index&pos=upload");
    		FileBody bin = new FileBody(new File("C:\\Users\\Administrator\\Downloads\\123.png"));
    		
    		StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
    		HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("fileName", bin).addPart("comment", comment).build();
    		httpPost.setEntity(reqEntity);
    		CloseableHttpResponse response = httpClient.execute(httpPost);
    		try {
    			HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                	System.out.println(response.getStatusLine());
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
			} finally{
				response.close();
			}
    	}finally{
    		httpClient.close();
    	}
    }
    
    /* SSL
     * 示例:ClientCustomSSL.java
     * */
    public final static void ssl() throws Exception {
    	// Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://localhost/");

            System.out.println("executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
    
    /* HTTP上下文
     * 示例:ClientCustomContext.java
     **/
    public final static void context() throws Exception {
    	CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建一个cookie存储的实例
            CookieStore cookieStore = new BasicCookieStore();
            
            // 创建本地HTTP上下文
            HttpClientContext localContext = HttpClientContext.create();
            // 绑定定义cookie存储到上下文
            localContext.setCookieStore(cookieStore);

            HttpGet httpget = new HttpGet("http://www.baidu.com/");

            // 将上下文作为参数
            CloseableHttpResponse response = httpclient.execute(httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                List<Cookie> cookies = cookieStore.getCookies();
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("Local cookie: " + cookies.get(i));
                }
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }


推荐博文

博文1

博文2


你可能感兴趣的:(HttpClient 学习记录)