Java发送Http请求,模拟表单上传文件

一、Maven引入httpclient、httpmime、httpclient-cache

二、表单内容

        <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
           <input type="text" name="param1" value="value1"/>
           <input type="text" name="param1" value="value1"/>
           <input type="file" name="file" value="value1"/>
           <input type="submit" value="submit"/>
        </form>

三、代码内容

        HttpClient httpClient = new DefaultHttpClient();
        HttpServletRequest request = ServletActionContext.getRequest();
        String sessionId = request.getRequestedSessionId();
        Enumeration paramNames = request.getParameterNames();
        MultipartEntity multipartEntity = new MultipartEntity();
        try {
            while (paramNames.hasMoreElements()) {
                String param = (String) paramNames.nextElement();
                String value = request.getParameter(param);
                StringBody body = new StringBody(value, Charset.forName("UTF-8"));
                multipartEntity.addPart(param, body);
            }
            if (installationPackage != null) {
                multipartEntity.addPart("installationPackage", new InputStreamBody(new FileInputStream(installationPackage), installationPackageFileName));
            }
            if (ico != null) {
                multipartEntity.addPart("ico", new InputStreamBody(new FileInputStream(ico), icoFileName));
            }
            String url = http://localhost:8080/management/StatisticsAction_uploadVersion";
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Cookie","JSESSIONID="+sessionId);
            httpPost.setEntity(multipartEntity);
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    JSONObject object = (JSONObject) JSONObject.parse(EntityUtils.toString(resEntity));
                    return (boolean) object.get("success");
                }
            }

        } finally {
            try {
                httpClient.getConnectionManager().shutdown();
            } catch (Exception e) {
                logger.error(e);
            }
        }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值