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

帅比萌擦擦* 提交于 2019-12-04 22:59:11

一、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);
            }
        }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!