0

I'm trying to create a Wordpress post via API using Java. So far I have the following code:

public class ConnessioneHttp {
   public void connect() throws Exception{
       URL url  = new URL(Constants.API_POST);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setRequestProperty("Authorization", "Bearer " + Constants.BEARER_TOKEN);
       conn.setRequestProperty("Content-Type", "application/json");
       conn.setRequestMethod("POST");
       conn.setDoOutput(true);
       String params = "?title=test from Java&content=lorem ipsum&status=publish";
       try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())){
            wr.writeBytes(parametri);
            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + params);
            System.out.println("Response Code : " + responseCode);
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
             String line;
             StringBuilder response = new StringBuilder();
             while ((line = in.readLine()) != null) {
                  response.append(line);
             }
             System.out.println(response.toString());
       }
   }
}

The method I'm calling this in is an action button that has this code:

@Override
        public void actionPerformed(ActionEvent e) {
            ConnessioneHttp conn = new ConnessioneHttp();
            try{
                conn.connect();
            } catch (Exception err){
                err.printStackTrace();
            }
        }

I've tried doing a GET request and it works fine, so I dont think the error is in the method I'm using to call the HttpRequest method (ConnessioneHttp).

I've tried using Postman and the post request with "http://localhost/project/wp-json/wp/v2/posts?title=test from Java&content=lorem ipsum&status=publish" works fine so I dont think the error is in the parameters either.

This is my first time with HTTP requests and Wordpress so I'm sure there are errors, I just can't figure out what I'm missing

This is the output I get:

Sending 'POST' request to URL : http://localhost/tesi/wp-json/wp/v2/posts
Post parameters : ?title=test da JAVA&content=lorem ipsum&status=publish
Response Code : 400
java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost/tesi/wp-json/wp/v2/posts
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1926)
    at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1921)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1920)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1490)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at it.unibas.progettotesi.modello.ConnessioneHttp.connect(ConnessioneHttp.java:55)
    at it.unibas.progettotesi.controllo.ControlloPanelPrincipale$AzioneHttp.actionPerformed(ControlloPanelPrincipale.java:64)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost/tesi/wp-json/wp/v2/posts
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
    at it.unibas.progettotesi.modello.ConnessioneHttp.connect(ConnessioneHttp.java:49)
    ... 38 more
fra
  • 23
  • 5
  • First you can try in PostMan rest client by passing the appropriate parameters, if it works then you can write the code. – PythonLearner Nov 09 '19 at 16:48

2 Answers2

0

400 Response code means your request is a bad/malformed request.

The only issue I can see here might be with the spaces. Url must not contain spaces. That's why they are replaced with %20. Postman might have done that for you behind the scenes.

Some useful links for you:

Spaces in URLs?

how to insert %20 in place of space in android

uneq95
  • 2,158
  • 2
  • 17
  • 28
  • are you sure that you need to send the data as request parameters and not in the request body? – uneq95 Nov 09 '19 at 18:15
0

I recommend try http-request built on apache http api.

final URL url  = new URL(Constants.API_POST);

final HttpRequest httpRequest = HttpRequestBuilder.create(httpClient).build();

private void connect(){
      WebTarget webTarget = httpRequest.target(uri)
          .addHeader("Authorization", "Bearer " + Constants.BEARER_TOKEN)
          .addHeader("Content-Type", "application/json")
          .addParameter("title", "test from Java")
          .addParameter("content", "lorem ipsum")
          .addParameter("status", "publish")
          //or instead addParameter you can use .addParameters("title=test from Java&content=lorem ipsum&status=publish") see the documentation

      //now you has two way first: 
     ResponseHandler<String> rh = webTarget.post(String.class)
     System.out.println(rh.getStatusCode());
     System.out.println(rh.get()); // response as string. also look at javadoc

     //Second: if you want to get response as stream use instead above
     Response response = webTarget.post()
     int statusCode = response.getStatusCode()
     InputStream inputStream = httpResponse.getEntity().getContent(); // Note forget that httpResponse.getEntity() can be null
}
Beno
  • 945
  • 11
  • 22