3

我想在我的 Android 应用程序中使用 Jersey 客户端。这是我的客户的代码:

private JSONArray getJsonElements(){
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    JSONArray jarray = new JSONArray();
     jarray =  service.path("/collection").accept(MediaType.APPLICATION_JSON).get(JSONArray.class);
     Log.v(TAG, jarray.toString());
    return jarray;
}
private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:6577/Example/rest/Example")
            .build();
}

问题来了。当我想构建应用程序时,它给了我这个非常常见的异常:

java.lang.IllegalArgumentException: already added: Ljavax/ws/rs/core/GenericEntity;...2012-07-07 16:48:32 - SM] Conversion to Dalvik format failed with error 1

我看到了有关此异常的所有问题。可以从 BuildPath 中删除 Jars 并更改客户端的选择(或者我可以创建我的客户端),但我不想这样做。你有什么可以推荐给我的?

4

1 回答 1

2

看看这个链接:http ://www.vogella.com/articles/AndroidNetworking/article.html

我自己更喜欢使用 HTTP 客户端将 Android 应用程序连接到使用 Jersey 的 Rest Service,因为它支持 HTTP 命令,例如 POST、PUT、DELETE、GET。例如使用 GET 命令并以 JSON 格式传输数据:

public class Client {

    private String server;

    public Client(String server) {
        this.server = server;
    }

    private String getBase() {
        return server;
    }

    public String getBaseURI(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet getRequest = new HttpGet(getBase() + str);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } 
        return result;
    }



 private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
            StringBuilder result = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
            String output;
            while ((output = br.readLine()) != null) 
                result.append(output);

            return result;      
      }
}

然后很容易在另一堂课上你可以:

Client client = new Client("http://localhost:6577/Example/rest/");
String str = client.getBaseURI("Example");    // Json format
于 2012-07-10T00:36:37.280 回答