码迷,mamicode.com
首页 > Web开发 > 详细

HTTPclient 4.2.2 传参数和文件流

时间:2018-11-27 21:00:06      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:exception   tps   catch   util   getc   对象   load   try   .exe   

package com.http;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class HttpClientUtil {

    @Test
    public void testHttp() {
        //创建HttpClient对象
        HttpClient client = new DefaultHttpClient();
        //构建POST请求   请求地址请更换为自己的。
        //1)
        HttpPost post = new HttpPost("XX");
       File file=new File("C:\\Users\\admin\\Desktop\\xidada.jpg");
        FileBody fileBody=new FileBody(file);
        try {
            StringBody name = new StringBody("xidada.jpg");
            MultipartEntity reqEntity = new MultipartEntity();
            StringBody bucketId = new StringBody("402880bd66a545e90166a545f3700000");
            reqEntity.addPart("bucketId", bucketId);//对应接口端的参数名称
            reqEntity.addPart("name", name);
            reqEntity.addPart("file", fileBody);//file1为请求后台的File upload;属性  
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == HttpStatus.SC_OK){
                
                System.out.println("服务器正常响应.....");
                
                HttpEntity resEntity = response.getEntity();
                
                
                System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据                
                System.out.println(resEntity.getContent());    
                EntityUtils.consume(resEntity);    
        }
        }catch (UnsupportedEncodingException e) {
            
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        }
       
    }
}

 

HTTPclient 4.2.2 传参数和文件流

标签:exception   tps   catch   util   getc   对象   load   try   .exe   

原文地址:https://www.cnblogs.com/woshuaile/p/10028513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!