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());
      }

   }

}

ご覧のとおり、私はジャージーを使用して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の2つのパブリックフィールドがあります。
  • LoginInfoクラスインスタンスを適切なuserIdとパスワードで初期化します
  • ログインコールに渡します

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は、セッター/ゲッターなどを備えた実際のBeanに変換できますが、単純に保ちたいだけです。それが機能するかどうかを確認してください...

于 2011-09-19T21:35:52.603 に答える
2

ジャージの代わりに、このコードはRestlet を使用して、Restを使用してActivitiと対話します。

このコードは、ActivitiinAction-第8章からのものです。すべてのクレジットはTijsRademakersに送られます。

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のcom.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:203)のcom.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:299)で見つかりませんでした.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:146)...8詳細

Mavenの依存関係にルーツを持つこともできます。私の場合、私は次のようなすべての単一のジャージーアーティファクトを置き換えることになりました

  • ジャージサーバー
  • jersey-json
  • ジャージ-クライアント

1つでjersey-bundle

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

jersey-multipart-1.19.jarへの依存関係を削除することで解決した同じ問題がありました。ジャージバンドルとマルチパートjarを含む共通の依存関係jarが作成されたときに、上記の例外が発生していました。それらを分離することで問題は解決しました。

于 2016-04-13T10:24:42.127 に答える
0

これは古い投稿ですが、HTTPClientバージョン4.1.3に基づいてコードを共有する必要があると思いました。ActivitiRESTで認証メカニズムを機能させるのと同様の問題がありました。この投稿では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);
}

変数名は自明だと思います。ありがとう

于 2014-04-11T04:54:40.753 に答える
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 に答える