Upload image + parameters HttpURLConnection

0

I have a Rest server and need to upload images and also send parameters. I've done a lot of research but I still can not make the client work. By the browser works right, via code I can send the image but the parameter does not. Follow the server code - Jersey 1.17.

@POST
@Path("/query")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload( @FormDataParam("file") InputStream fileInputStream, 
                        @FormDataParam("file") FormDataContentDisposition contentHeader, 
                        @FormDataParam("codvendedor") String codVendedor)
{
    System.out.println("Rep"+codVendedor);
    String path = "C:\arquivosXML\"+contentHeader.getFileName();

    System.out.println("path "+path);

    saveFile(fileInputStream, path);

    String output = "File saved";
    return Response.status(Response.Status.OK).entity(output).build();
}

Follow the client

public void post2() throws MalformedURLException, IOException
{
    String paramToSend = "4";
    File fileToUpload = new File("C:\doc\fachada2.png");
    String boundary = Long.toHexString(System.currentTimeMillis()); 
    String userCredentials = "rep4:44";

    String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes()));

    HttpURLConnection  connection = (HttpURLConnection) new URL(URL_UPLOAD  ).openConnection();
    connection.setDoOutput(true); // This sets request method to POST.

    connection.setRequestMethod("POST");
    connection.setRequestProperty ("Authorization", basicAuth);
    connection.setRequestProperty ("Connection", "keep-alive");
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);


    DataOutputStream  output = null;
    try
    {
        output = new DataOutputStream (connection.getOutputStream());
        output.writeBytes("--" + boundary+"\r\n");
        output.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"fachada2.png\""+"\r\n");
        output.writeBytes("Content-Type: image/png;"+"\r\n");
        output.writeBytes("\r\n");

        byte[] anexo = convertInputstreamToBytes(fileToUpload);
        output.write(anexo);

        output.writeBytes("--" + boundary+"\r\n");
        output.writeBytes("Content-Disposition: form-data; name=\"codvendedor\""+"\r\n");
        output.writeBytes("Content-Type: text/plain; charset=UTF-8"+"\r\n");
        output.writeBytes(paramToSend+"\r\n");

        output.writeBytes("--" + boundary + "--" + "\r\n");
    }
    finally
    {
        if (output != null)
        {
            output.flush();
            output.close();
        }
    }


    int responseCode = ((HttpURLConnection) connection).getResponseCode();
    System.out.println(responseCode); 
}
    
asked by anonymous 13.05.2015 / 22:58

0 answers