Send string by Post from client to Java server Jersey

1

I try to send 2 string from my java client to my java server using Jersey, the client and the server respond correctly (code 200),

  

Server Code

@POST
@Path("eliminar")
@Consumes({ MediaType.MULTIPART_FORM_DATA, ("text/plain") }) 
@Produces(MediaType.APPLICATION_JSON) 
public String eliminar(
        @FormDataParam("primero") String primero,
        @FormDataParam("segundo") String segundo){  
    System.out.println("recibiendo primero "+primero+ " segundo "+segundo);
    return "Rastalovely";
}
  

Client Code

package eliminar;
import java.io.*;
import java.net.*;
import java.util.*;
public class Limpio {
    final static String URL = "http://localhost:8080/restdemo/jaxrs/customers/eliminar";
    public static void main(String[] args) {
        String crlf = "\r\n";
        String twoHyphens = "--";
        try {
            String boundary = "--" + Long.toString(System.currentTimeMillis()) + "--";
            String parametros="primero=primero&segundo=segundo";        
            byte[] postDataBytes = parametros.toString().getBytes();

            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream request = new DataOutputStream(connection.getOutputStream());    
            request.writeBytes(twoHyphens + boundary + crlf);
            request.writeBytes(parametros);
            System.out.println("responseCode " + connection.getResponseCode());

            //Aqui java retorna
            BufferedReader in =new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb=new StringBuffer();
            String line;
            while((line=in.readLine())!=null){
                    sb.append(line);
            }
            in.close();
            System.out.println("salida "+sb.toString());            
        } catch (Exception e) {
            System.out.println("error " + e.getMessage());
        }
    }
}

The results: When the client runs, I get the variables on the server console as null and on the client side if he receives the message from the server.

So I do not know if the way I send the variables is correct.

    
asked by Rastalovely 29.04.2018 в 23:39
source

2 answers

2

You are sending the information as it would be sent in a normal HTTP request; but you want to work with multipart/form-data .

The format of your message should be something like:

Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=DEADBEEF
--DEADBEEF
Content-Disposition: form-data; name="primero"

primero
--DEADBEEF
Content-Disposition: form-data; name="segundo"

segundo

--DEADBEEF--

Apart from the obvious change of parameters, a couple of notes:

  • You are using multipart/form-data but it does not seem necessary. Unless you are going to use it later (to send attachments, for example), I would vote to eliminate it.

  • Unless there are technical or legal incompatibilities, or it is an exercise, it is always good to use a library that is already in charge of management at a low level, such as Apache's HTTP Components

  • It seems that you are not closing the message "--" + delimitador + "--" .

  • I do not say it's an error, but I would not put "-" as part of the delimiter.

answered by 30.04.2018 в 10:42
0

After investigating and using Java Jersey as a client, you can solve my problem, then publish my answer.

import java.io.File;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

public class principal {

    public static void main(String[] args) {
            try {
                String URL="http://localhost:8080/restdemo/jaxrs/customers/upload";
                Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
                FileDataBodyPart filePart = new FileDataBodyPart("MyFile", new File("C:/Users/Rastalovely/Desktop/imagen.png"));
                FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
                FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
                        .field("llave1", "campo1")
                        .field("llave2", "campo2")
                        .bodyPart(filePart);
                WebTarget target = client.target(URL);
                String json = target.request(MediaType.APPLICATION_JSON).post(Entity.entity(multipart, multipart.getMediaType()), String.class);
                System.out.println("answer :"+json);
                formDataMultiPart.close();
                multipart.close();
            } catch (Exception e) {
                System.out.println(e);
            }
    }
}
    
answered by 07.05.2018 в 15:33