Java tutorial
/* * Copyright 2010 shanyong.wang Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in * writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.anteam.demo.logback.appender; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.AppenderBase; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class HttpAppender<E> extends AppenderBase<E> { private static final HttpClient httpclient = new DefaultHttpClient(); private String url; @Override protected void append(E event) { System.out.println(((LoggingEvent) event).getFormattedMessage()); StringEntity stringEntity = new StringEntity(event.toString(), ContentType.create("text/plain", "UTF-8")); HttpPost post = new HttpPost(url); post.setEntity(stringEntity); HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // Examine the response status System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = null; try { instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response System.out.println(reader.readLine()); } catch (Exception ex) { post.abort(); } finally { try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Override protected void finalize() throws Throwable { super.finalize(); httpclient.getConnectionManager().shutdown(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }