开发者

send array from web service(jersey) to client(HTTP)

I have implement a web service using jersey and I have a client making HTTP requests. The web service talks with a database. When the client makes a request, the server through a query retrieves some data from the database(list of contacts). I would like to return these data to the client(as a response). So now i am just trying to send a simple sting array from server to client.

Server Code:

package de.vogella.jersey.first;
import java.util.ArrayList;
import javax.ws.rs.FormParam;
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;
@Path("/hello2")
public class Hello2 {
//String msg3[] = {"one", "two"}; 
//ArrayList<String> listitems = new ArrayList<String>();

String msg2 = "message of the server";
// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
    System.out.println("TEXT_PLAIN is request Hello_2");
    return "Hello Jersey from Hello_2";
}

@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)   
public String[] authedication(@FormParam("username") String us, @FormParam("password") String pass){ 

    String msg3[] = {"one", "two"}; 
    System.out.println("these are the results of the Hello2");
    System.out.println("--------------------------------------------------");
    System.out.println("The name is \"" + us + "\" is request");
    System.out.println("The password is \"" + pass + "\" is request");
    System.out.println("--------------------------------------------------");

    return msg3;
}

}

Client Code:

  public void addContactsToList(){
  Log.v(TAG, "Load contacts");
  HttpClient client = new DefaultHttpClient();
  EditText etxt_user = (EditText) findViewById(R.id.username);
  EditText etxt_pass = (EditText) findViewById(R.id.password);
  String username1 = etxt_user.getText().toString();
  String password1 = etxt_pass.getText().toString();
  HttpPost httppost = new HttpPost("http://10.0.2.2:8080/de.vogella.jersey.first/rest/hello2");
  Log.v(TAG, "message1");         
  //add your Data
  List< NameValuePair > nvps = new ArrayList< NameValuePair >();
  nvps.add(new BasicNameValuePair("username", username1));
  nvps.add(new BasicNameValuePair("password", password1));

  try {
        UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

        httppost.setEntity(p_entity);
        //Execute HTTP Post Request
        Log.v(TAG, "The request has been sent.");
        HttpResponse response = client.execute(httppost);

        Log.v(TAG, response.getStatusLine().toString());
        HttpEntity responseEntity = response.getEntity();
        //final InputStream inputStream = responseEntity.getContent();

        String x = EntityUtils.toString(responseEntity);

        Log.v(TAG,x);
        removeDialog(1);
        Intent intent=new Intent(getApplicationContext(),TestM_chat4_all_contacts.class);
        intent.putExtra("Contacts",x);
        startActivity(intent);

  } catch (Exception e)
  {
        Intent intent = new Intent(getApplicationContext(), LoginError.class);//calls the activity LoginError.java
        intent.putExtra("LoginMessage", "Unable to load your contacts");
        startActivity(intent);
        removeDialog(0);
   }

}

So can i send an array or an arraylist from the server and how the client reads these data? Also I am thinking to use JSON, is this implemantation(send array) possible using JSON?

Thank you in Ad开发者_Python百科vance!


On server you shoud produce JSON

@Produces(MediaType.APPLICATION_JSON)

Then on client you can use Gson to convert it automatically to Java types. For array you'd use

String[] result = gson.fromJson(x, String[].class); 


I'm doing a similar thing in my app. I have an object in php that contains an array (though a multi-dimensional array should work similarly). The object looks like this

object(Object)#24 (1) {
  ["content"]=>
  array(2) {
    ["id"]=>
    string(3) "365"
    ["text"]=>
    string(76) "Here is some text"
  }
}

The object is formated as a json string using php's json_encode() function and returned to the client. On the client side Android app I'm doing something like this

import org.json.JSONException;
import org.json.JSONObject;
...

HttpGet request = new HttpGet(getUrl);

try {
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    HttpClient client = new DefaultHttpClient();
    String responseBody = client.execute(request, responseHandler);

    try {
        JSONObject getJObject = new JSONObject(responseBody);
        JSONObject contentObject = getJObject.getJSONObject("content");
        getText = contentObject.getString("id");
        getTextId = contentObject.getString("text");
    } catch (JSONException e) {
        e.printStackTrace();
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

This is just making a GET request to the server but the response from a POST request can be used just the same.

I'm storing the elements from the resulting array as strings but you can easily add them to an array instead by replacing the above code

getText = contentObject.getString("text");
getTextId = contentObject.getString("id");

with something closer to

yourArray[0] = contentObject.getString("id");
yourArray[1] = contentObject.getString("text");  

I hope that helps a bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜