c#作客户端使用http协议的post上传json数据到Java服务端,接收返回结果并打出

参数:id,string。data,string(json转换的string)。time,string(例20200107000000)。namefile,file(图片名字的集合)

参考:

string _url = "https://www.dXXXayup.ink/api/User/Login";
            //json参数
            string jsonParam = "{ phonenumber:\"18665885202\",pwd:\"tsp\"}";
            var request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
            int length = byteData.Length;
            request.ContentLength = length;
            Stream writer = request.GetRequestStream();
            writer.Write(byteData, 0, length);
            writer.Close();
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            MessageBox.Show(responseString.ToString());

c# 客户端

private void UploadRequest(string url, string filePath)
{
    // 时间戳,用做boundary
    string timeStamp = DateTime.Now.Ticks.ToString("x");
    //根据uri创建HttpWebRequest对象
    HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create(new Uri(url));
    httpReq.Method = "POST";
    httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
    httpReq.Timeout = 300000; //设置获得响应的超时时间(300秒)
    httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp;
    //文件
    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    BinaryReader binaryReader = new BinaryReader(fileStream);
    //头信息
    string boundary = "--" + timeStamp;
    string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
    string header = string.Format(dataFormat, "file", Path.GetFileName(filePath));
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header);
    //结束边界
    byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
    long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
    httpReq.ContentLength = length; //请求内容长度
    try
    {
        //每次上传4k
        int bufferLength = 4096;
        byte[] buffer = new byte[bufferLength];
        //已上传的字节数
        long offset = 0;
        int size = binaryReader.Read(buffer, 0, bufferLength);
        Stream postStream = httpReq.GetRequestStream();
        //发送请求头部消息
        postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
        while(size > 0)
        {
            postStream.Write(buffer, 0, size);
            offset += size;
            size = binaryReader.Read(buffer, 0, bufferLength);
        }
        //添加尾部边界
        postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        postStream.Close();
        //获取服务器端的响应
        using(HttpWebResponse response = (HttpWebResponse) httpReq.GetResponse())
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string returnValue = readStream.ReadToEnd();
            MessageBox.Show(returnValue);
            response.Close();
            readStream.Close();
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine("文件传输异常: " + ex.Message);
    }
    finally
    {
        fileStream.Close();
        binaryReader.Close();
    }
}

Java服务端

public Map saveCapture(HttpServletRequest request, HttpServletResponse response, Map config) throws Exception
{
    response.setContentType("text/html;charset=UTF-8");
    // 读取请求Body
    byte[] body = readBody(request);
    // 取得所有Body内容的字符串表示
    String textBody = new String(body, "ISO-8859-1");
    // 取得上传的文件名称
    String fileName = getFileName(textBody);
    // 取得文件开始与结束位置
    String contentType = request.getContentType();
    String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
    // 取得实际上传文件的气势与结束位置
    int pos = textBody.indexOf("filename=\"");
    pos = textBody.indexOf("\n", pos) + 1;
    pos = textBody.indexOf("\n", pos) + 1;
    pos = textBody.indexOf("\n", pos) + 1;
    int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
    int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
    int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;
    //保存到本地
    writeToDir(fileName, body, begin, end);
    response.getWriter().println("Success!");
    return config;
}
private byte[] readBody(HttpServletRequest request) throws IOException
{
    // 获取请求文本字节长度
    int formDataLength = request.getContentLength();
    // 取得ServletInputStream输入流对象
    DataInputStream dataStream = new DataInputStream(request.getInputStream());
    byte body[] = new byte[formDataLength];
    int totalBytes = 0;
    while(totalBytes < formDataLength)
    {
        int bytes = dataStream.read(body, totalBytes, formDataLength);
        totalBytes += bytes;
    }
    return body;
}
private String getFileName(String requestBody)
{
    String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
    fileName = fileName.substring(0, fileName.indexOf("\n"));
    fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));
    return fileName;
}
private void writeToDir(String fileName, byte[] body, int begin, int end) throws IOException
{
    FileOutputStream fileOutputStream = new FileOutputStream("d:/" + fileName);
    fileOutputStream.write(body, begin, (end - begin));
    fileOutputStream.flush();
    fileOutputStream.close();
}

我看了楼上的回答,你在客户端的没问题了;
服务端的话,用java也是好实现的;
如果想简便的话,直接用springboot + mybatis-plus 即可。