gpt4 book ai didi

java - 将 Jersey 客户端添加到我的 Android 应用程序。发生非法参数异常?

转载 作者:太空狗 更新时间:2023-10-29 13:35:09 25 4
gpt4 key购买 nike

我想在我的 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 并更改客户端的选择(或者我可以创建我的客户端),但我不想这样做。你能给我推荐什么?

最佳答案

查看此链接:http://www.vogella.com/articles/AndroidNetworking/article.html

我自己更喜欢使用 HTTP 客户端将 Android 应用程序连接到使用 Jersey 的 Rest 服务,因为它支持 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

关于java - 将 Jersey 客户端添加到我的 Android 应用程序。发生非法参数异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com