Httpclient4.4之原理(请求执行)(5)

HttpClient提供了几个通过HTTP connection有效地流出内容的类。这些类的实例与POST和PUT这样的entity enclosing requests有关,为了把这些实体内容放进即将发出的请求中。HttpClient提供的这几个类大多数都是数据容器,像字符串,字节数组,输入流和文件对应的:StringEntity,ByteArrayEntity,InputStreamEntity和FileEntity。示例:

File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
 

请注意:InputStreamEntity是不可重复的,因为它只能从底层数据流读一次。通常推荐使用InputStreamEntity来实现一个自定义的self-contained的HttpEntity类。

7.1 HTML表单

许多应用程序需要模拟提交一个HTML表单的过程,例如,为了登录一个web应用程序或者提交输入数据,HttpClient提供一个实体类UrlEncodedFormEntity来帮助完成这个过程。

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
 

这UrlEncodedFormEntity实体将使用URL编码来编码参数并产生如下内容:

param1=value1&param2=value2
 

7.2 HTTP分块

通常推荐HttpClient选择适当的基于HTTP消息传输特性的传输编码。然而,有个可能是通知HttpEntity优先使用分块编码(chunk coding),通过HttpEntity的setChunked()方法设置为true。请注意,HttpClient使用此标记仅仅是为了提示。当使用HTTP协议不支持分块编码时,这个值将被忽略,如:HTTP/1.0。示例:
 
StringEntity entity = new StringEntity("important message",
    ContentType.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<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {
            @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);
    }
}

使用HttpClient实现文件的上传下载

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/9e6df74f30b5635d9e9708bc9e48a617.html