0

I have the below code on the Java client Side which is calling a Spring Based REST service,I get a HTTP 400 Error .But it works perfect with the POST man Client

Java Client :

  public void getData(String ip){
        try{
            JSONObject json=new JSONObject();
            json.put("time_range", "22-23");
            json.put("flow_id", "786");
            json.put("ip_a", "192.65.78.22");
            json.put("port_a", "8080");
            json.put("regex", "%ab");




            URL url=new URL("http://"+ip+":8080/pcap");
            HttpURLConnection httpcon=(HttpURLConnection)url.openConnection();
            httpcon.setDoOutput(true);
            httpcon.setRequestMethod("POST");
            httpcon.setRequestProperty("Accept", "application/json");
            httpcon.setRequestProperty("Content-Type", "application/json");

            httpcon.setRequestProperty("Accept", "application/json");


            OutputStreamWriter output=new OutputStreamWriter(httpcon.getOutputStream());
            System.out.println(json);
            output.write(json.toString());
            httpcon.connect();

            String output1=httpcon.getResponseMessage();
            System.out.println(output1);

        }catch(Exception e){

        }

The server side REST Service Code is

@RequestMapping(value = URIConstansts.PCAP, produces = { "application/json" }, method = RequestMethod.POST)
public  ResponseEntity getPcap(HttpServletRequest request,@RequestBody PcapParameters pcap_params )

Now when the client sends a request it gives me http 400 error ,and it may be because on client side im sending JSON string while on the server side its a body ,but this works on POST MAN

enter image description here

Can anyone please suggest how can I send a POST request to a spring based REST service via Java

arpit joshi
  • 1,987
  • 8
  • 36
  • 62
  • If using Spring, you should use [Rest Template](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/remoting.html#rest-resttemplate) – Ori Dar Sep 26 '15 at 10:55

1 Answers1

0

400 Error code represents Bad data. What you can do,if you can put logs on server side what you are getting after http call.

For better implementations, refer Http open connection to send data

Community
  • 1
  • 1
  • But request does not reach the server side method – arpit joshi Sep 26 '15 at 11:09
  • Request is able to reach server side. only issue is that server requires some data and its nt getting. So bad request error(400) not 404(page not found). Try to put character set con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // ... OutputStream os = con.getOutputStream(); os.write(parent.toString().getBytes("UTF-8")); os.close(); – Dharmendra Vishwakarma Sep 26 '15 at 11:21
  • String is not working ,sending a json string gives a 400 on server side – arpit joshi Sep 26 '15 at 12:06