ntentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true); //设置为分块编码
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);
?
8. response处理
处理response最简单,最方便的方式是使用ResponseHandler接口,它包含handleResponse(HttpResponse respnse)方法。这种方法让用户完全不用担心连接的管理。使用ResponseHandler时,HttpClient将自动释放连接并把连接放回连接管理器中,不论请求执行成功还是失败。示例:
?
package httpclienttest;
?
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
?
public class T14 {
? ? public static void main(String[] args) {
? ? ? ? CloseableHttpClient httpclient = HttpClients.createDefault();
? ? ? ? HttpGet httpget = new HttpGet("http://localhost/json");
? ? ? ? ResponseHandler rh = new ResponseHandler() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public JsonObject handleResponse(final HttpResponse response)throws IOException {
? ? ? ? ? ? ? ? StatusLine statusLine = response.getStatusLine();
? ? ? ? ? ? ? ? HttpEntity entity = response.getEntity();
? ? ? ? ? ? ? ? if (statusLine.getStatusCode() >= 300) {
? ? ? ? ? ? ? ? ? ? throw new HttpResponseException(statusLine.getStatusCode(),
? ? ? ? ? ? ? ? ? ? ? ? ? ? statusLine.getReasonPhrase());
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (entity == null) {
? ? ? ? ? ? ? ? ? ? throw new ClientProtocolException("Response contains no content");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? Gson gson = new GsonBuilder().create();
? ? ? ? ? ? ? ? ContentType contentType = ContentType.getOrDefault(entity);
? ? ? ? ? ? ? ? Charset charset = contentType.getCharset();
? ? ? ? ? ? ? ? Reader reader = new InputStreamReader(entity.getContent(), charset);
? ? ? ? ? ? ? ? return gson.fromJson(reader, MyJsonObject.class);
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? MyJsonObject myjson = httpclient.execute(httpget, rh);
? ? }
}