下面我给出httpclient4的官网例子的详细解释:作者@author:huanglei_jmr,转载请注明
package cn.huanglei_jmr.demo;
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
importorg.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.params.CoreConnectionPNames;
public class AsyncClientHttpExchangeFutureCallback {
publicstatic void main(String[] args) throws Exception {
HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.getParams()
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,3000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 *1024)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
httpclient.start();
try {
HttpGet[] requests = new HttpGet[] {
new HttpGet("http://www.apache.org/"),
new HttpGet("https://www.verisign.com/"),
new HttpGet("http://www.google.com/")
};
final CountDownLatch latch = newCountDownLatch(requests.length);
for (final HttpGet request: requests) {
httpclient.execute(request, new FutureCallback() {
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" +response.getStatusLine());
}
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" + ex);
}
public void cancelled() {
latch.countDown();
System.out.println(request.getRequestLine() + " cancelled");
}
});
}
latch.await();
System.out.println("Shutting down");
} finally {
httpclient.shutdown();
}
System.out.println("Done");
}
}
2:
package cn.huanglei_jmr.demo;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
importorg.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
public class AsyncClientHttpExchange {
publicstatic void main(String[] args) throws Exception {
HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
HttpGet request = new HttpGet("http://www.apache.org/");
Future future = httpclient.execute(request, null);
HttpResponse respOnse= future.get();
//System.out.println(response.getAllHeaders());
System.out.println("Response: " + response.getStatusLine());
System.out.println("Shutting down");
} finally {
httpclient.shutdown();
}
System.out.println("Done");
}
}
3:
package cn.huanglei_jmr.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
importorg.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
public class AsyncClientHttpExchangeStreaming {
private static FileOutputStream out;
public static void main(String[] args) throwsException {
HttpAsyncClient httpclient =new DefaultHttpAsyncClient();
httpclient.start();
try {
File file =new File("d:/JAVA/jmr.html");
out = newFileOutputStream(file);
//excute(请求发送者,响应接受者,回调函数),它这个用的是泛型的那个execute方法,我这里不嫩直接得到response啊
//嘿嘿,不是有“响应接受者”吗,通过它来拿响应的数据啊
Future future= httpclient.execute(
HttpAsyncMethods.createGet("http://localhost:8080/"),
newMyResponseConsumer(), null);
Booleanresult = future.get();
if (result !=null && result.booleanValue()) {
System.out.println("Requestsuccessfully executed");
} else{
System.out.println("Requestfailed");
}
System.out.println("Shuttingdown");
} finally {
httpclient.shutdown();
}
System.out.println("Done");
}
static class MyResponseConsumer extendsAsyncCharConsumer {
@Override
protected voidonResponseReceived(final HttpResponse response) {
}
@Override
protected void onCharReceived(final CharBuffer buf, final IOControlioctrl) throws IOException {
//我一直改,想把tomcat的主页写到我的文件中去,相当于截取了一个网页,但是没成功,出现数组超标,但是下一个程序就给我解决了这个需求
//我的猜测又对了buf.get();这个函数取一个自己,CharBuffer长度就少1,难怪用hasremain判断
System.out.println(buf.length());
// 不写while(),输出一个< 一个字节,说明它是一个字节一个字节输出的,没有缓存
System.out.println(buf.get());
System.out.println(buf.length());
}
@Override
protected voidreleaseResources() {
}
@Override
protected BooleanbuildResult(final HttpContext context) {
returnBoolean.TRUE;
}
private byte[]getBytes(CharBuffer cb) {
Charset cs =Charset.forName("UTF-8");
//CharBuffercb = CharBuffer.allocate(chars.length);
//cb.put(chars);
//cb.flip();
ByteBuffer bb= cs.encode(cb);
returnbb.array();
}
}
//我自己在网上找的一个将byte[]转为char[]代码
private char[] getChars(byte[] bytes) {
Charset cs =Charset.forName("UTF-8");
ByteBuffer bb =ByteBuffer.allocate(bytes.length);
bb.put(bytes);
bb.flip();
CharBuffer cb =cs.decode(bb);
return cb.array();
}
}
4:
package cn.huanglei_jmr.demo;
import java.io.File;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.entity.ContentType;
importorg.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.ZeroCopyConsumer;
import org.apache.http.nio.client.methods.ZeroCopyPost;
public class ZeroCopyHttpExchange {
publicstatic void main(String[] args) throws Exception {
HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
File upload = new File("d:/JAVA/jmr.html");
File download = new File("d:/JAVA/hl.html");
//怎么样查看的到我的上传文件就好了,没找到方法
ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload,
ContentType.create("text/plain"));
ZeroCopyConsumer cOnsumer= new ZeroCopyConsumer(download) {
@Override
protected File process(
final HttpResponse response,
final File file,
final ContentType contentType) throws Exception {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
throw new ClientProtocolException("Upload failed: " +response.getStatusLine());
}
return file;
}
};
Future future = httpclient.execute(httpost, consumer, null);
File result = future.get();
System.out.println("Response file length: " +result.length());
System.out.println("Shutting down");
} finally {
httpclient.shutdown();
}
System.out.println("Done");
}
}