3

编辑:为了简化我的问题,有没有人设法使用 rest 与 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 服务,这是我一直得到的响应:

引用:

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

非常感谢,

4

6 回答 6

4

尝试以下操作:

  • 在依赖项中包含 jersey-json 模块
  • 创建一个名为 LoginInfo 的新类,使用 @XmlRootElement 注释进行注释,具有两个公共字段 - userId 和 password
  • 使用正确的 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,只是想保持简单。看看有没有效果...

于 2011-09-19T21:35:52.603 回答
2

作为球衣的替代品,此代码使用Restlet 与使用 Rest 的 Activiti 交互。

此代码来自Activiti in Action-第 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;
    }
....
}
于 2012-06-15T09:41:56.260 回答
1

错误

引起:com.sun.jersey.api.client.ClientHandlerException:Java 类型、com.sun.jersey.core.util.MultivaluedMapImpl 类和 MIME 媒体类型 application/x-www-form-urlencoded 的消息正文编写器,在 com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:203) 在 com.sun 的 com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:299) 中找不到.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:146) ... 还有 8 个

它也可以根植于 Maven 依赖项。就我而言,我最终替换了所有单一的泽西文物,比如

  • 球衣服务器
  • 球衣-json
  • 球衣客户

与一个jersey-bundle

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.14</version>
    </dependency>
于 2012-09-28T05:28:27.337 回答
1

我有同样的问题,通过删除对 j​​ersey-multipart-1.19.jar 的依赖得到解决。当构建一个包含 jersey bundle 和 multipart jar 的通用依赖 jar 时,我遇到了上述异常。分开他们解决了这个问题。

于 2016-04-13T10:24:42.127 回答
0
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;
    }
}
于 2014-09-12T08:51:22.850 回答
0

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

创建 HTTP 客户端。请注意,它还会创建 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);
}

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

于 2014-04-11T04:54:40.753 回答