httpClient 请求


import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.Consts;
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.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import net.sf.json.JSONObject;

public class ClientUtil {


    private static final String FAR_SERVICE_DIR = "http://192.168.10.88:8080/getService";
    private static final long yourMaxRequestSize = 10000000;

    public  Logger logger = LoggerFactory.getLogger(this.getClass());

    public String upload(HttpServletRequest request) throws Exception {
        // 判断enctype属性是否为multipart/form-data
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart)
            throw new IllegalArgumentException(
                    "上传内容不是有效的multipart/form-data类型.");

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置上传内容的大小限制(单位:字节)
        upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        List<?> items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                // 如果是普通表单字段
                String name = item.getFieldName();
                String value = item.getString();
                // ...
            } else {
                // 如果是文件字段
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // ...

                // 上传到远程服务器
                HashMap<String, FileItem> files = new HashMap<String, FileItem>();
                files.put(fileName, item);
                uploadToFarServiceByHttpClient(files);
            }
        }
        return "redirect:/";
    }

    private void uploadToFarServiceByHttpClient(HashMap<String, FileItem> files) {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost(FAR_SERVICE_DIR);
            MultipartEntity reqEntity = new MultipartEntity();
            Iterator iter = files.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                FileItem val = (FileItem) entry.getValue();
                FileBody filebdody = new FileBody(inputstreamtofile(
                        val.getInputStream(), key));
                reqEntity.addPart(key, filebdody);
            }
            httppost.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                System.out.println("服务器正常响应.....");
                HttpEntity resEntity = response.getEntity();
                System.out.println(EntityUtils.toString(resEntity,"UTF-8"));// httpclient自带的工具类读取返回数据
                EntityUtils.consume(resEntity);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {

            }
        }

    }

    public File inputstreamtofile(InputStream ins, String filename)
            throws IOException {
        File file = new File(filename);
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }



    public static void upload2() throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8081/sys/TestData");
        httpPost.setConfig(requestConfig);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        //multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

        //File file = new File("F:\\Ken\\1.PNG");
        //FileBody bin = new FileBody(file); 

        File file = new File("E:\\destdir\\新建文本文档.txt");

        //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
        //当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
        //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
        multipartEntityBuilder.addBinaryBody("file",file);
        //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addTextBody("comment", "this is comment");
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);

        httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        int statusCode= httpResponse.getStatusLine().getStatusCode();
        if(statusCode == 200){
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String str = "";
            while(!"".equals(str = reader.readLine())) {
                buffer.append(str);
            }

            System.out.println(buffer.toString());
        }

        httpClient.close();
        if(httpResponse!=null){
            httpResponse.close();
        }

    }

    public static void main(String[] args) {
//        File file = new File("E:\\destdir\\协助查询财产通知书.jpg");
//        Map<String, String> params = new HashMap();
//        params.put("fileName", file.getName());
//        params.put("userId", "25252525");
//        String url = "http://127.0.0.1:8081/sys/uploadFile";
//        String result = post(url,params,file);
    	
    	String invokeUrl="http://10.12.223.230:8581/GatewayMsg/rest/invoke";
    	String	userName="wangqigong";
    	String	certNo="350301198906180060";
    	String	deptNo="5555";
    	String	szzsbm="555";
    	String senderId="C00-20000004";
    	String serviceId="S10-20000070";
    	String task_period = "60";
    	String json = "{\"endUser\":\"wangqigong,350301198906180060,5555,555\"}";
    
//    	String result = post2(invokeUrl,senderId,serviceId,json,task_period);
//    	System.out.println(result);
    	
    	Map<String, String> params = new HashMap<String,String>();
    	RestTemplate template = new RestTemplate();
    	HttpHeaders httpHeaders = new HttpHeaders();
    	httpHeaders.add("sender_id", senderId);
    	httpHeaders.add("service_id", serviceId);
    	//请求用户信息
    	try {
    	    //中文需要先编码、不然获取会乱码
    	    httpHeaders.add("fingerprint", "{\"endUser\":\""+ URLEncoder.encode(userName,"UTF-8")+","+certNo+","+deptNo+","+szzsbm+"\"}");
    	} catch (UnsupportedEncodingException e) {
    	    e.printStackTrace();
    	}
    	//任务超时时间
    	httpHeaders.add("task_period", "60");
    	String body = null;
    	org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<String>(body, httpHeaders);
    	try {
    	    System.out.println("fsdfs");
    	    ResponseEntity<String> responseEntity = template.exchange(invokeUrl, HttpMethod.GET, requestEntity, String.class, params);
    	    String resulr = responseEntity.getBody();
    	    int i = responseEntity.getStatusCode().value();
    	    System.out.print(i+"========="+resulr);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
      	
    	
    }

    /**
     * client的post传文件
     * @param url
     * @param params
     * @param file
     * @return
     */
    public String post(String url,Map<String, String> params,File file) {
       String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httppost = new HttpPost(url);
            

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            StringBody comment = new StringBody("This is comment", ContentType.create("text/plain", Consts.UTF_8));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            setUploadParams(multipartEntityBuilder, params);
            if(file != null){
            	FileBody bin = new FileBody(file);
            	HttpEntity reqEntity = multipartEntityBuilder.addPart("multipartFile", bin).addPart("comment", comment).build();
            	httppost.setEntity(reqEntity);
            }else{
            	HttpEntity reqEntity = multipartEntityBuilder.addPart("comment", comment).build();
            	httppost.setEntity(reqEntity);
            }
//            HttpEntity reqEntity = multipartEntityBuilder.addPart("file", bin).addPart("comment", comment).build();

//            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(response.getEntity());
//                    System.out.println(result);
//                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 设置请求参数
     * @param multipartEntityBuilder
     * @param params
     */
    private static void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,  Map<String, String> params) {
        if (params != null && params.size() > 0) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                multipartEntityBuilder .addPart(key, new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
            }
        }
    }
    
    /**
     * get请求
     * @param invokeUrl
     * @param senderId
     * @param serviceId
     * @param json
     * @param task_period
     * @param userName
     * @param certNo
     * @param deptId 单位代码
     * @param szzsbm
     * @return
     */
    public  String get(String invokeUrl, String senderId, String serviceId,  String task_period,String userName,String certNo,String deptId,String szzsbm ) {
     	String resultUrl = "";
    	Map<String, String> params = new HashMap<String,String>();
    	RestTemplate template = new RestTemplate();
    	HttpHeaders httpHeaders = new HttpHeaders();
    	httpHeaders.add("sender_id", senderId);
    	httpHeaders.add("service_id", serviceId);
    	//请求用户信息
    	try {
    	    //中文需要先编码、不然获取会乱码
    	    httpHeaders.add("fingerprint", "{\"endUser\":\""+ URLEncoder.encode(userName,"UTF-8")+","+certNo+","+deptId+","+szzsbm+"\"}");
    	  //任务超时时间
        	httpHeaders.add("task_period", task_period);
        	String body = null;
        	org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<String>(body, httpHeaders);
        	System.out.println("fsdfs");
     	    ResponseEntity<String> responseEntity = template.exchange(invokeUrl, HttpMethod.GET, requestEntity, String.class, params);
     	    int i = responseEntity.getStatusCode().value();
     	   logger.info("请求状态:"+i);
     	    if(i == 200){
     	    	String resulr = responseEntity.getBody();
     	    	JSONObject jsonObj = JSONObject.fromObject(resulr);
     	    	resultUrl = jsonObj.get("url").toString();
     	    }
    	} catch (UnsupportedEncodingException e) {
    	    e.printStackTrace();
    	}
    	
    	return resultUrl;
      	
     }
    
    
    public  String getToSendCode(String url,Map<String, String> params, Map<String,String> paramHead) {
    	String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httppost = new HttpPost(url);
            

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            setUploadParams(multipartEntityBuilder, params);
           
            HttpEntity reqEntity = multipartEntityBuilder.build();
        	httppost.setEntity(reqEntity);
        	httppost.setHeader("stepNum", paramHead.get("stepNum"));
        	httppost.setHeader("receiveAppId", paramHead.get("receiveAppId"));
        	httppost.setHeader("invokingAppId", paramHead.get("invokingAppId"));
        	httppost.setHeader("processNum", paramHead.get("processNum"));

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(response.getEntity());
//                    System.out.println(result);
//                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
      	
     }
     

}

httpmime-4.5.3.jar

httpclient-4.5.3.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值