简体   繁体   中英

Post to server using Java restlet

I am trying to post to server a JSONO bject, using restlet. When I try to post using the POSTMAN it is able to post, but when I try to post from the java code using the restlet I get an error as:

Unable to find a converter for this object and Bad Request (400) - The request could not be understood by the server due to malformed syntax.

My code is:

ClientResource resource = new ClientResource(localHost + "/path");

//resource.setMethod(Method.POST);
resource.setAttribute("Authorization", authHdr); //auth code passed to the function 
resource.setAttribute("Accept", "application/json");
resource.setAttribute("Content-Type", "application/json");

Map<Integer, JSONObject> assetGrpList = networks; //map I pass to function
for(Iterator<Map.Entry<Integer, JSONObject>> it = assetGrpList.entrySet().iterator(); it.hasNext();)
{
    Map.Entry<Integer, JSONObject> mapEntry = it.next();
    JSONObject network = mapEntry.getValue();

    JSONObject jsonobj = new JSONObject();

    jsonobj.put("managedSiteId", siteId);
    jsonobj.put("assetGrpExternalId", network.get("NetworkID").toString());
    jsonobj.put("assetGrpName", network.get("NetworkName"));
    jsonobj.put("geoLocationInfoId", 1);
    log.info(jsonobj.toString());

    Representation response = resource.post(jsonobj, MediaType.APPLICATION_JSON); 
    if(resource.getResponse().getStatus().getCode() > 200) {
        try {
            log.info(response.getText());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


org.restlet.resource.ResourceException: Bad Request
at org.restlet.resource.ClientResource.doError(ClientResource.java:590)
at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1153)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1048)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1023)
at org.restlet.resource.ClientResource.post(ClientResource.java:1485)
at org.restlet.resource.ClientResource.post(ClientResource.java:1424)
at com.waygum.mbaas.connectors.helper.MbaasRestClient.postAssetGrp(MbaasRestClient.java:531)
at com.waygum.mbaas.connectors.MbaasConnectorsBootRouter$1.process(MbaasConnectorsBootRouter.java:229)
at org.apache.camel.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:63)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:141)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:87)
at org.apache.camel.component.sparkrest.CamelSparkRoute.handle(CamelSparkRoute.java:46)
at spark.SparkBase$1.handle(SparkBase.java:311)
at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:159)
at spark.webserver.JettyHandler.doHandle(JettyHandler.java:60)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745)

I think that you are creating the request the wrong way. You should use the Restlet API to do that.

ClientResource resource = new ClientResource(localHost + "/path");

resource.setAttribute("Authorization", authHdr); //auth code passed to the function 

// JSON payload and Content-Type header

JSONObject jsonObj = (...)
JsonRepresentation repr = new JsonRepresentation(jsonObj);

// Authorization header

String pAccessToken = "some token";
ChallengeResponse challengeResponse = new ChallengeResponse(
                  new ChallengeScheme("", ""));
challengeResponse.setRawValue(pAccessToken);
resource.setChallengeResponse(challengeResponse);

// Request and Accept header

resource.post(jsonObj, MediaType.APPLICATION_JSON);

The representation automatically contains the application/json content type since it's a JSON one. The second parameter defines the value of the Accept header.

Regarding the Authorization header, HTTP requires a prefix like Basic . That's why Restlet requires one in its API. As a workaround you can pass an empty prefix. See this answer for more details:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM