使用Activiti Rest Web服务的问题

发布于 2024-12-05 06:43:53 字数 3195 浏览 4 评论 0原文

编辑:为了简化我的问题,有没有人设法与 Activiti 使用休息?如果是的话,请您发布您的代码。 谢谢。

我一直在努力使用 Rest 登录 Activiti。我遵循 api 指南并实现了以下

代码:

package demo;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider;

public class Aloha {

   /**
    * @param args
    */
   public static void main(String[] args) {
      // TODO Auto-generated method stub

      Client client = Client.create();
      WebResource webResource = client
            .resource("http://localhost:8080/activiti-rest/service/login");
      MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
      formData.add("userId", "kermit");
      formData.add("password", "kermit");
      ClientResponse response;
      try {
         response = webResource.type("application/x-www-form-urlencoded")
               .post(ClientResponse.class, formData); // webResource.accept(MediaType.TEXT_PLAIN_TYPE).post(ClientResponse.class,
                                             // formData);
         System.out.print(response.toString());
      } catch (UniformInterfaceException ue) {
         System.out.print(ue.getMessage());
      }

   }

}

如您所见,我正在使用 Jersey 来使用 Web 服务,这是我一直得到的响应:

Quote:

POST http://localhost:8080/activiti-rest/service/login returned a response status of 415 Unsupported Media Type

请您指出我在这里做错了什么?

请注意,当我用“application/json”替换类型时,我收到以下错误:

代码:

Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type, application/json, was not found
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
   at com.sun.jersey.api.client.Client.handle(Client.java:648)
   at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
   at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
   at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
   at demo.Aloha.main(Aloha.java:32)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type, application/json, was not found
   at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
   ... 5 more

非常感谢,

Edit: to simplify my question, has anyone managed to communicate with
Activiti using rest?, and if so could you be kind to post your code.
thanks.

I've been struggeling for a while to login to Activiti using Rest. I followed the api guides and implemented the following

Code:

package demo;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider;

public class Aloha {

   /**
    * @param args
    */
   public static void main(String[] args) {
      // TODO Auto-generated method stub

      Client client = Client.create();
      WebResource webResource = client
            .resource("http://localhost:8080/activiti-rest/service/login");
      MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
      formData.add("userId", "kermit");
      formData.add("password", "kermit");
      ClientResponse response;
      try {
         response = webResource.type("application/x-www-form-urlencoded")
               .post(ClientResponse.class, formData); // webResource.accept(MediaType.TEXT_PLAIN_TYPE).post(ClientResponse.class,
                                             // formData);
         System.out.print(response.toString());
      } catch (UniformInterfaceException ue) {
         System.out.print(ue.getMessage());
      }

   }

}

As you can see I am using Jersey to consume the webservice, and here is the response I am getting all time:

Quote:

POST http://localhost:8080/activiti-rest/service/login returned a response status of 415 Unsupported Media Type

Please could you point out what I am doing wrong here?

Please note that when I replace the type with "application/json" i get the follow error:

Code:

Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type, application/json, was not found
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
   at com.sun.jersey.api.client.Client.handle(Client.java:648)
   at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
   at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
   at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
   at demo.Aloha.main(Aloha.java:32)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type, application/json, was not found
   at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
   at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
   ... 5 more

Many Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

沧桑㈠ 2024-12-12 06:43:53

尝试以下操作:

  • 在依赖项中包含 jersey-json 模块
  • 创建一个名为 LoginInfo 的新类,使用 @XmlRootElement 注释进行注释,具有两个公共字段 - userId 和密码 使用
  • 正确的 userId 和密码初始化 LoginInfo 类实例
  • 将其传递给登录调用

这是 LoginInfo 类的代码:

@XmlRootElement
public class LoginInfo {
    public String userId;
    public String password;
}

这是 main() 方法的代码:

  Client client = Client.create();
  WebResource webResource = client
        .resource("http://localhost:8080/activiti-rest/service/login");
  LoginInfo loginInfo = new LoginInfo();
  loginInfo.userId = "kermit";
  loginInfo.password = "kermit";
  ClientResponse response;
  try {
     response = webResource.type("application/json").post(ClientResponse.class, loginInfo);
     System.out.print(response.toString());
  } catch (UniformInterfaceException ue) {
     System.out.print(ue.getMessage());
  }

注意: 我还没有尝试过这个,也许有一些拼写错误等等。另外,LoginInfo 可以变成一个带有 setter/getter 之类的真正的 bean,只是想保持简单。看看是否有效...

Try the following:

  • Include jersey-json module in your dependencies
  • Create a new class named LoginInfo, annotated with @XmlRootElement annotation, having two public fields - userId and password
  • Initialize the LoginInfo class instance with the right userId and password
  • Pass it to the login call

Here is the code for the LoginInfo class:

@XmlRootElement
public class LoginInfo {
    public String userId;
    public String password;
}

Here is the code for the main() method:

  Client client = Client.create();
  WebResource webResource = client
        .resource("http://localhost:8080/activiti-rest/service/login");
  LoginInfo loginInfo = new LoginInfo();
  loginInfo.userId = "kermit";
  loginInfo.password = "kermit";
  ClientResponse response;
  try {
     response = webResource.type("application/json").post(ClientResponse.class, loginInfo);
     System.out.print(response.toString());
  } catch (UniformInterfaceException ue) {
     System.out.print(ue.getMessage());
  }

Note: I haven't tried this, maybe there are some typos or so. Also the LoginInfo can be turned into a real bean with setters/getters and stuff, just wanted to keep it simple. See if it works...

记忆で 2024-12-12 06:43:53

作为 jersey 的替代方案,此代码使用 Restlet 使用 Rest 与 Activiti 进行交互。

此代码来自 Activiti 的实际应用 - 第 8 章。所有功劳都应归功于 Tijs Rademakers。

public class ActivitiRestClient {

    private static String REST_URI = "http://localhost:8080/activiti-rest/service";
    private static Logger logger = Logger.getLogger(ActivitiRestClient.class);

    private static ClientResource getClientResource(String uri) {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,
                "kermit", "kermit");
        return clientResource;
    }
....
}

As an alternative to jersey, This code uses Restlet to interact with Activiti using Rest.

This code are from Activiti in Action- Chapter 8. All credit should goes to Tijs Rademakers.

public class ActivitiRestClient {

    private static String REST_URI = "http://localhost:8080/activiti-rest/service";
    private static Logger logger = Logger.getLogger(ActivitiRestClient.class);

    private static ClientResource getClientResource(String uri) {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,
                "kermit", "kermit");
        return clientResource;
    }
....
}
反目相谮 2024-12-12 06:43:53

错误

由:com.sun.jersey.api.client.clienthandlerexception:一条消息
Java类型的身体作家,班级
com.sun.jersey.core.util.multivaluedmapimpl和Mime Media类型,
Application/x-www-form-urlenCoded,在
com.sun.jersey.api.client.requestwriter.writerequestentity(requestWriter.java:299)

com.sun.jersey.client.urlconnection.urlconnectionclienthandler._invoke(urlConnectionClientHandler.java:203)

com.sun.jersey.client.urlconnection.urlconnectionclienthandler.handle(urlConnectionClientHandler.java:146)
... 8更多

还可以根深蒂固的依赖性。就我而言,我最终用一个泽西 - 巴尼(Jersey-Bundle)替换了所有单一的球衣工具,例如

  • 泽西郡
  • 泽西 - 杰森·泽西
  • - 泽西 - 泽西式

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.14</version>
    </dependency>

The error

Caused by: com.sun.jersey.api.client.ClientHandlerException: A message
body writer for Java type, class
com.sun.jersey.core.util.MultivaluedMapImpl, and MIME media type,
application/x-www-form-urlencoded, was not found at
com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:299)
at
com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:203)
at
com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:146)
... 8 more

can also have it roots in maven dependencies. In my case I ended up replacing all the single Jersey artifacts like

  • jersey-server
  • jersey-json
  • jersey-client

with one jersey-bundle.

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.14</version>
    </dependency>
尾戒 2024-12-12 06:43:53

我遇到了同样的问题,这些问题通过消除了对泽西 - 米尔特帕特1.19.jar的依赖而解决的问题。当建立一个共同的依赖罐(包括泽西束和多部分罐子)时,我会得到上述例外。分开他们解决了问题。

I had the same issue which got solved by removing the dependency on jersey-multipart-1.19.jar. I was getting the above exception when a common dependency jar was built which included the jersey bundle and the multipart jar. Separating them solved the issue.

抽个烟儿 2024-12-12 06:43:53

虽然这是一篇旧文章,但我认为我应该分享基于 HTTPClient 版本 4.1.3 的代码。我在使用 Activiti REST 获取身份验证机制时遇到了类似的问题。虽然这篇文章涵盖了基于 Jersey 和 Restlet 的解决方案,但我认为发布基于 HTTPClient 的解决方案会很有帮助。

创建 HTTPClient。请注意,它还创建 TargetHost(用于执行操作:

public HttpClient createHttpClient() {

targetHost = new HttpHost(REST_HOST_NAME, REST_PORT, REST_PROT);

Credentials defaultcreds = new UsernamePasswordCredentials(USERNAME, PWD);

AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

HttpClient client = new DefaultHttpClient();
((DefaultHttpClient)client).getCredentialsProvider().setCredentials(authScope, defaultcreds);
 return client;
}

创建 HTTP 上下文:

public BasicHttpContext createLocalContext() {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();

// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
return localContext;
}

添加方法来获取目标主机:

public HttpHost getTargetHost() {
//created in the createHttpClient Method
return this.targetHost;
}

最后调用 REST:

public JSONObject invokeGetWS() throws ClientProtocolException, IOException {
ResponseHandler<String> responseHandler = new BasicResponseHandler();

HttpClient client = createHttpClient();

HttpGet httpGet = new HttpGet(ws_url); 
//ws_url is created at run time e.g http://localhost:9090/activiti-rest/service/user/kermit
System.out.println("executing request: " + httpGet.getRequestLine());

String responseBody = client.execute(getTargetHost(), httpGet, responseHandler, createLocalContext());
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");

return new JSONObject(responseBody);
}

我想变量名称是不言自明的。
谢谢

Though this is an old post but I thought I should share my code based on HTTPClient version 4.1.3. I had a similar problem getting authentication mechanism work with Activiti REST. Though this post covers solutions based on Jersey and Restlet, I thought it would be helpful to post a solution based on HTTPClient.

Create the HTTPClient. Please note that it also creates the TargetHost (which is used to execute an action:

public HttpClient createHttpClient() {

targetHost = new HttpHost(REST_HOST_NAME, REST_PORT, REST_PROT);

Credentials defaultcreds = new UsernamePasswordCredentials(USERNAME, PWD);

AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

HttpClient client = new DefaultHttpClient();
((DefaultHttpClient)client).getCredentialsProvider().setCredentials(authScope, defaultcreds);
 return client;
}

Create HTTP Context:

public BasicHttpContext createLocalContext() {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();

// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
return localContext;
}

Add a method to get the target host:

public HttpHost getTargetHost() {
//created in the createHttpClient Method
return this.targetHost;
}

Finally invoke the REST:

public JSONObject invokeGetWS() throws ClientProtocolException, IOException {
ResponseHandler<String> responseHandler = new BasicResponseHandler();

HttpClient client = createHttpClient();

HttpGet httpGet = new HttpGet(ws_url); 
//ws_url is created at run time e.g http://localhost:9090/activiti-rest/service/user/kermit
System.out.println("executing request: " + httpGet.getRequestLine());

String responseBody = client.execute(getTargetHost(), httpGet, responseHandler, createLocalContext());
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");

return new JSONObject(responseBody);
}

I suppose the variable names would be self explanatory.
Thanks

想念有你 2024-12-12 06:43:53
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

public static boolean getAuthenticationSuccess(String username, String password) throws Exception {
    String uri = REST_URI + "/login";
    JSONStringer jsRequest = new JSONStringer();
    jsRequest.object();
    jsRequest.key("userId").value(username);
    jsRequest.key("password").value(password);
    jsRequest.endObject();
    Representation rep = new JsonRepresentation(jsRequest);
    rep.setMediaType(MediaType.APPLICATION_JSON);
    ClientResource clientResource = new ClientResource(uri);

    try {
        JSONObject jsObj = new JSONObject(clientResource.post(rep).getText());
        return jsObj.getBoolean("success");
    } catch (Exception e) {
        // TODO: handle exception
        logger.info("Erreur " + e.getMessage());

        return false;
    }
}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.MediaType;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

public static boolean getAuthenticationSuccess(String username, String password) throws Exception {
    String uri = REST_URI + "/login";
    JSONStringer jsRequest = new JSONStringer();
    jsRequest.object();
    jsRequest.key("userId").value(username);
    jsRequest.key("password").value(password);
    jsRequest.endObject();
    Representation rep = new JsonRepresentation(jsRequest);
    rep.setMediaType(MediaType.APPLICATION_JSON);
    ClientResource clientResource = new ClientResource(uri);

    try {
        JSONObject jsObj = new JSONObject(clientResource.post(rep).getText());
        return jsObj.getBoolean("success");
    } catch (Exception e) {
        // TODO: handle exception
        logger.info("Erreur " + e.getMessage());

        return false;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文