0

我是 Android 编程新手,我需要实现一个 Android resteasy-mobile 客户端。我需要连接远程 JAX-RS Web 服务。我正在搜索周围,但找不到简单的示例客户端。你能告诉我如何制作一个 Android resteasy-mobile 客户端吗?

先感谢您。

4

1 回答 1

1

最后,我决定使用 Jersey 服务器实现一个 Android json (Jackson) 客户端。如果有人需要知道它是怎么回事,这是我的代码:

服务器:

package com.sl;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sl.model.pojo.UserLocation;

@Path("/json/service")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public UserLocation getTrackInJSON() {

        UserLocation ul = new UserLocation();
        ul.setCodigo("1");
        ul.setLatitud(Float.valueOf("1.1"));
        ul.setLongitud(Float.valueOf("1.2"));

        return ul;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(UserLocation userLocation) {

        String result = "Record saved.";
        return Response.status(201).entity(result).build();

    }

}

web.xml

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>

<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
        <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.sl</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

客户:

ReceiveFeedTask.java

package android.jaxrs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;

import android.jaxrs.model.pojo.UserLocation;
import android.os.AsyncTask;
import android.util.Log;

public class RetreiveFeedTask extends AsyncTask<String, String, Boolean> {

    private static String TAG = "ReceiveFeedTask";
    private  String jaxrsmessage = null;

    private static String IP = "191.162.1.107"; //IP CASA
    //private static String IP = "10.0.2.2"; //IP LOCALHOST

    private static String DIRECCION_GET = "http://" + IP + ":8080/ServidorLoc/rest/json/service/get";
    private static String DIRECCION_POST = "http://" + IP + ":8080/ServidorLoc/rest/json/service/post";

    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected Boolean doInBackground(String... params) {
        HttpClient httpclient = null;


        try {
             android.os.Debug.waitForDebugger();
             httpclient = new DefaultHttpClient();


             HttpGet request = new HttpGet(DIRECCION_GET);

             request.addHeader("Content-Type", "application/json");
             request.addHeader("Accept", "application/json");
             HttpResponse response = httpclient.execute(request);
             HttpEntity entity = response.getEntity();
             InputStream instream = entity.getContent();
             jaxrsmessage = read(instream);
             Log.d(TAG, jaxrsmessage);


             //POST
             UserLocation ul= new UserLocation(); 
             ul.setCodigo("2");
             ul.setLatitud(Float.valueOf("2.1"));
             ul.setLongitud(Float.valueOf("2.2"));

             String json = mapper.writeValueAsString(ul);



             HttpPost post = new HttpPost(DIRECCION_POST);
             post.setHeader("Content-Type", "application/json");
             StringEntity se = new StringEntity(json);
             post.setEntity(se);
             HttpResponse httpResponse = new DefaultHttpClient().execute(post);
             String retSrc = EntityUtils.toString(httpResponse.getEntity());
             Log.d(TAG, retSrc);


        } catch (ClientProtocolException e) {
            Log.e(TAG, "Se ha producido un error: " + e.toString() + "\nMensaje: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "Se ha producido un error: " + e.toString() + "\nMensaje: " + e.getMessage());
        } catch (Exception e){
            Log.e(TAG, "Se ha producido un error: " + e.toString() + "\nMensaje: " + e.getMessage());
        }finally {
            httpclient.getConnectionManager().shutdown();
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private static String read(InputStream instream) {
        StringBuilder sb = null;
        try {
             sb = new StringBuilder();
             BufferedReader r = new BufferedReader(new InputStreamReader(
                   instream));
             for (String line = r.readLine(); line != null; line = r.readLine()) {
                sb.append(line);
             }

            instream.close();
            r.close();

        } catch (IOException e) {
            Log.e(TAG, "Se ha producido un error: " + e.toString() + "\nMensaje: " + e.getMessage());
        }
        return sb.toString();

   }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.jaxrs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="android.jaxrs.AndroidJAXRSClient"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

就这样!!!:)

于 2013-04-06T09:58:43.107 回答