使用http MultipartEntityBuilder发送请求 MultipartEntity实现文件上传的客户端和服务端

 使用http  MultipartEntityBuilder发送请求

//MultipartEntityBuilder发送请求方法体
//号码导入接口
    public static String  importnumber(Map<String,Object> datastr,String tokenid){
        //供应商提供的接口地址
        String url = "http://192.168.1.1:8080/interface.php?func=importnumber";
        String charset = "UTF-8";
        JSONObject jsonObject = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            Map<String,Object> resultMap = new HashMap<String,Object>();
            //把一个普通参数和文件上传给下面这个地址    是一个servlet
            HttpPost httpPost = new HttpPost(url);
            //设置传输参数
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            //设计文件以外的参数
            Set<String> keySet = datastr.keySet();
            for (String key : keySet) {
                //相当于<input type="text" name="name" value=name>
                multipartEntity.addPart(key, new StringBody((String) datastr.get(key), ContentType.create("text/plain", Consts.UTF_8)));
            }
            HttpEntity reqEntity =  multipartEntity.build();
            httpPost.setEntity(reqEntity);
            //Logger.info("发起请求的页面地址 " + httpPost.getRequestLine());
            //发起请求   并返回请求的响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                //log.info("----------------------------------------");
                //打印响应状态
                //log.info(response.getStatusLine());
                resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                //获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //打印响应长度
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    //log.info("Response content length: " + resEntity.getContentLength());
                    //打印响应内容
                    resultMap.put("data", EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
                }
                //销毁
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }


            //RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();//设置请求和传输超时时�?
            //HttpPost httppost = new HttpPost(url.trim());
            //httppost.setConfig(requestConfig);
            //if (datastr != null) {
            //    if (charset != null) {
            //        httppost.setEntity(new StringEntity(datastr, charset));
            //    } else {
            //        httppost.setEntity(new StringEntity(datastr));
            //    }
            //}
            //CloseableHttpResponse response = httpclient.execute(httppost);
            String result = null;

            //if(response.getStatusLine().getStatusCode()==200){
            //    result = EntityUtils.toString(response.getEntity());
            //    jsonObject = JSONObject.parseObject(result);
            //    System.out.println(result);
            //}
            //httpclient.close();
            System.out.println("导入号码完成");
        }
        //try {
        //    CloseableHttpClient httpclient = HttpClients.createDefault();
        //    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();//设置请求和传输超时时�?
        //    HttpPost httppost = new HttpPost(url.trim());
        //    httppost.setConfig(requestConfig);
        //    if (datastr != null) {
        //        if (charset != null) {
        //            httppost.setEntity(new StringEntity(datastr, charset));
        //        } else {
        //            httppost.setEntity(new StringEntity(datastr));
        //        }
        //    }
        //    CloseableHttpResponse response = httpclient.execute(httppost);
        //    String result = null;
        //
        //    if(response.getStatusLine().getStatusCode()==200){
        //        result = EntityUtils.toString(response.getEntity());
        //        jsonObject = JSONObject.parseObject(result);
        //        System.out.println(result);
        //    }
        //    httpclient.close();
        //    System.out.println("导入号码完成");
        //}


        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "导入号码完成";
    }



//调用方法开始位置
public static void SendPhone(List<HashMap<String, String>> phoneList) throws UnsupportedEncodingException {

        Map<String,Object> json = new HashMap<String,Object>();
        JSONObject json2 = new JSONObject();
        String tokenid = getTokenId();
        String prjid = getPrjid(tokenid);
        String subid = createsubscribe(tokenid,prjid,"未检测人员外呼");
        Array array[] = {};
        for (int i = 0; i < phoneList.size(); i ++) {
            String phones = phoneList.get(i).get("phone");
            System.out.println("i=" + i + ",phones:" + phones);
            json2.put(phoneList.get(i).get("phone"),array);
        }
        //json2.put("19163321515",array);
        json.put("tokenid",tokenid);
        json.put("prjid",prjid);
        json.put("subid",subid);
        json.put("total", Integer.toString(phoneList.size()));
        json.put("data",encode(json2).trim());
        json.put("duplicates","1");
        //importnumber(json.toJSONString(),tokenid);
        importnumber(json,tokenid);
        System.out.println("结束");
    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用HttpClient发送带文件和参数的POST请求,您可以按照以下步骤进行操作: 1. 导入所需的类: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; 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.HttpClients; ``` 2. 创建HttpClient实例: ```java HttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost请求对象: ```java HttpPost httpPost = new HttpPost(url); ``` 其中,`url`是目标URL。 4. 创建MultipartEntityBuilder对象,并添加文件和参数: ```java MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(file)); // 添加文件 builder.addPart("param1", new StringBody(param1, ContentType.TEXT_PLAIN)); // 添加参数1 builder.addPart("param2", new StringBody(param2, ContentType.TEXT_PLAIN)); // 添加参数2 ``` 其中,`file`是要上传的文件,`param1`和`param2`是需要传递的参数。 5. 构建HttpEntity并设置给HttpPost请求对象: ```java HttpEntity multipartEntity = builder.build(); httpPost.setEntity(multipartEntity); ``` 6. 执行HttpPost请求并获取响应: ```java HttpResponse response = httpClient.execute(httpPost); ``` 7. 处理响应结果: ```java int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); // 处理响应实体 ``` 完整的示例代码如下: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; 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.HttpClients; import java.io.File; import java.io.IOException; public class HttpClientExample { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file"; String param1 = "value1"; String param2 = "value2"; HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(new File(filePath))); builder.addPart("param1", new StringBody(param1, ContentType.TEXT_PLAIN)); builder.addPart("param2", new StringBody(param2, ContentType.TEXT_PLAIN)); HttpEntity multipartEntity = builder.build(); httpPost.setEntity(multipartEntity); try { HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); // 处理响应实体 } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,上述示例中使用的是Apache HttpClient 4.x版本。在使用之前,请确保已经添加相关的依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值