利用HttpClient发送基于Content-Type="multipart/form-data"形式的表单

一、利用HttpClient发送基于Content-Type="multipart/form-data"形式的表单

package com.test.httpclient;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.commons.httpclient.HttpClient;

publicclass SendXmlAction
{
    public String execute() throws ServletException, IOException
    {
        String xmlhead = this.getRequest().getParameter("xmlhead");
        String xmlbody = this.getRequest().getParameter("xmlbody");
        System.out.println("xmlhead == "+xmlhead);
        System.out.println("xmlbody == "+xmlbody);
        
        // 用远程服务的URL设置生成POST方法,供HTTP客户端执行
        String remoteUrl = "http://**.**.***.***:8888/project/receiveServlet";
        
        PostMethod method = new PostMethod(remoteUrl);
        
        // multipart/form-data; boundary=---------------------------7de2b13a790640
        
        //method.addParameter("xmlhead", xmlhead);
        //method.addParameter("xmlbody", xmlbody);        
        HttpClient HTTP_CLINET = new HttpClient();
        
        synchronized (HTTP_CLINET)
        {
            try
            {
                //使用多重发送方式,发送两个独立的两个XML Part,基于Content-Type="multipart/form-data"形式的表单
                Part[] parts = {new StringPart("xmlhead",xmlhead), new StringPart("xmlbody",xmlbody)}; //StringPart和FilePart都可以放进去
                RequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());
                method.setRequestEntity(requestEntity);
                
                method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
                //链接超时 30秒
                HTTP_CLINET.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
                //读取超时 30秒
                HTTP_CLINET.getHttpConnectionManager().getParams().setSoTimeout(30000);
                
                HTTP_CLINET.executeMethod(method);
                
                String[] result = new String[2];
                result[0] = String.valueOf(method.getStatusCode());
                result[1] = method.getResponseBodyAsString();
                System.out.println("http status : "+result[0]);
                System.out.println("http response : "+result[1]);
                
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (method != null)
                {
                    method.releaseConnection();
                }
                method = null;
            }
        }
        
        return "success";
    }
}

 

二、MultipartRequest接收参数

package com.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oreilly.servlet.MultipartRequest;

publicclass BossServlet extends HttpServlet
{

    /** serialVersionUID */private Logger logger = Logger.getLogger(BossServlet.class);

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException
    {
        this.doPost(request, response);
    }

    protectedvoid doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {        
        // MultipartRequest
        String head = null ;
        String body = null ;
        
        try
        {
            File fileDir = new File(this.getServletContext().getRealPath("/formhttp"));
            if (!fileDir.exists())
            {
                fileDir.mkdirs();
            }
            
            int inmaxPostSize = 10 * 1024 * 1024;
            
            // utf-8中文编码模式上传文件
            MultipartRequest multirequest = new MultipartRequest(request,fileDir.getAbsolutePath(),inmaxPostSize,"UTF-8"); 
            
            head = multirequest.getParameter("head");
            body = multirequest.getParameter("body");
            System.out.println("xmlHead2 = " + xmlHead);
            System.out.println("xmlBody2 = " + xmlBody);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/mixed;boundary=---------------------------7de2b13a790640"); 
        PrintWriter out = response.getWriter();

        String res = null;
        try
        {
            res = .....
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        if (!(res == null || "".equals(res)))
        {
            try
            {
                out.println(res);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                out.close();
            }

        }
    }

    publicvoid init() throws ServletException
    {
        super.init();
    }
}

 若发送基于Content-Type="multipart/form-data"形式的表单,却通过request.getParameter("**")获取参数值,则获取的参数值为空。

在C#中,当你需要通过`HttpClient`发送`multipart/form-data`类型的表单数据时,你需要在请求中明确设置`Content-Type`头以及构造`HttpContent`实例来表示文件和其他键值对。下面是一个示例: ```csharp using System.Net.Http; using System.IO; // 创建HttpClient实例 HttpClient client = new HttpClient(); // 设置Content-Typemultipart/form-data MultipartFormDataContent formData = new MultipartFormDataContent(); formData.Add(new StringContent("key1", Encoding.UTF8, "text/plain")); // 文本键值对 // 添加二进制文件(假设你有一个名为"file.jpg"的本地文件) string filePath = "path_to_your_file.jpg"; FileStream fileStream = File.OpenRead(filePath); HttpContent fileContent = new StreamContent(fileStream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); formData.Add(fileContent, "file", Path.GetFileName(filePath)); // 发送POST请求 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://your-api-url.com/upload") { Content = formData }; try { HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); // 检查响应状态码 // 处理响应... } catch (HttpRequestException ex) { // 处理网络或请求错误... } // 关闭流,释放资源 if (fileStream != null) { fileStream.Close(); } ``` 在这个例子中,我们首先创建了一个`MultipartFormDataContent`容器,然后添加了文本键值对和文件作为`HttpContent`的一部分。最后,我们在`HttpRequestMessage`中设置了这个`Content`属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值