HttpClient4 基本操作

文件上传

/** 
 * 上传文件 
 *  
 * @throws ParseException 
 * @throws IOException 
 */  
public static void postFile() throws ParseException, IOException {  
    CloseableHttpClient httpClient = HttpClients.createDefault();  
    try {  
        // 要上传的文件的路径  
        String filePath = new String("C:\\Users\\zz\\Desktop\\diqu.png");  
        // 把一个普通参数和文件上传给下面这个地址 是一个servlet  
        HttpPost httpPost = new HttpPost(  
                "http://xx.xx.xx.xxs:8081/auth_center/upload");  
        // 把文件转换成流对象FileBody  
        File file = new File(filePath);  
        FileBody bin = new FileBody(file);  
        /*StringBody uploadFileName = new StringBody("my.png", 
                ContentType.create("text/plain", Consts.UTF_8));*/  
        // 以浏览器兼容模式运行,防止文件名乱码。  
        HttpEntity reqEntity = MultipartEntityBuilder.create()  
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)  
                .addPart("uploadFile", bin) // uploadFile对应服务端类的同名属性<File类型>  
                //.addPart("uploadFileName", uploadFileName)// uploadFileName对应服务端类的同名属性<String类型>  
                .setCharset(CharsetUtils.get("UTF-8")).build();  

        httpPost.setEntity(reqEntity);  

        System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());  
        // 发起请求 并返回请求的响应  
        CloseableHttpResponse response = httpClient.execute(httpPost);  
        try {  
            // 打印响应状态  
            System.out.println(response.getStatusLine());  
            // 获取响应对象  
            HttpEntity resEntity = response.getEntity();  
            if (resEntity != null) {  
                // 打印响应长度  
                System.out.println("Response content length: "  
                        + resEntity.getContentLength());  
                // 打印响应内容  
                System.out.println(EntityUtils.toString(resEntity,  
                        Charset.forName("UTF-8")));  
            }  
            // 销毁  
            EntityUtils.consume(resEntity);  
        } finally {  
            response.close();  
        }  
    } finally {  
        httpClient.close();  
    }  
}  

文件下载

/** 
 * 下载文件 
 *  
 * @param url 
 *            http://www.xxx.com/img/333.jpg 
 * @param destFileName 
 *            xxx.jpg/xxx.png/xxx.txt 
 * @throws ClientProtocolException 
 * @throws IOException 
 */  
public static void getFile(String url, String destFileName)  
        throws ClientProtocolException, IOException {  
    // 生成一个httpclient对象  
    CloseableHttpClient httpclient = HttpClients.createDefault();  
    HttpGet httpget = new HttpGet(url);  
    HttpResponse response = httpclient.execute(httpget);  
    HttpEntity entity = response.getEntity();  
    InputStream in = entity.getContent();  
    File file = new File(destFileName);  
    try {  
        FileOutputStream fout = new FileOutputStream(file);  
        int l = -1;  
        byte[] tmp = new byte[1024];  
        while ((l = in.read(tmp)) != -1) {  
            fout.write(tmp, 0, l);  
            // 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试  
        }  
        fout.flush();  
        fout.close();  
    } finally {  
        // 关闭低层流。  
        in.close();  
    }  
    httpclient.close();  
}  

读取压缩文件

public static void readZipFile(String file) throws Exception {  
       ZipFile zf = new ZipFile(file);  
       InputStream in = new BufferedInputStream(new FileInputStream(file));  
       ZipInputStream zin = new ZipInputStream(in);  
       ZipEntry ze;  
       while ((ze = zin.getNextEntry()) != null) {  
           if (ze.isDirectory()) {
           } else {  
               System.err.println("file - " + ze.getName() + " : "  
                       + ze.getSize() + " bytes");  
               long size = ze.getSize();  
               if (size > 0) {  
                   BufferedReader br = new BufferedReader(  
                           new InputStreamReader(zf.getInputStream(ze)));  
                   String line;  
                   while ((line = br.readLine()) != null) {  
                       System.out.println(line);  
                   }  
                   br.close();  
               }  
               System.out.println();  
           }  
       }  
       zin.closeEntry();  
   }  

Post Json数据

HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(json.toString());
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);

示例:

public static String httpPostWithJSON(String url) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

//        json方式
        JSONObject jsonParam = new JSONObject();  
        jsonParam.put("name", "admin");
        jsonParam.put("pass", "123456");
        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题    
        entity.setContentEncoding("UTF-8");    
        entity.setContentType("application/json");    
        httpPost.setEntity(entity);
        System.out.println();


//        表单方式
//        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 
//        pairList.add(new BasicNameValuePair("name", "admin"));
//        pairList.add(new BasicNameValuePair("pass", "123456"));
//        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   


        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he,"UTF-8");
        }
        return respContent;
    }


    public static void main(String[] args) throws Exception {
        String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
        System.out.println(result);
    }

设置超时时间


RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000).setConnectTimeout(10000)
.setConnectionRequestTimeout(10000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig); //或则Get

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值