从Web服务(泽西)发送数组到客户端(HTTP)

时间:2011-09-13 18:31:42

标签: android

我使用jersey实现了一个Web服务,我有一个客户端发出HTTP请求。 Web服务与数据库进行通信。当客户端发出请求时,服务器通过查询从数据库中检索一些数据(联系人列表)。我想将这些数据返回给客户端(作为响应)。所以现在我只是想从服务器向客户端发送一个简单的sting数组。

服务器代码:

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

}

客户代码:

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

}

那么我可以从服务器发送一个数组或一个arraylist以及客户端如何读取这些数据?另外我想使用JSON,这个实现(发送数组)是否可以使用JSON?

提前谢谢你!

2 个答案:

答案 0 :(得分:0)

在服务器上,您应该生成JSON

@Produces(MediaType.APPLICATION_JSON)

然后在客户端上,您可以使用Gson将其自动转换为Java类型。对于array,您可以使用

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

答案 1 :(得分:0)

我在我的应用程序中做了类似的事情。 我在php中有一个包含数组的对象(尽管多维数组应该类似)。该对象看起来像这样

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

使用php的json_encode()函数将对象格式化为json字符串并返回给客户端。 在客户端Android应用程序我正在做这样的事情

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

这只是向服务器发出GET请求,但POST请求的响应可以使用相同的。

我将结果数组中的元素存储为字符串,但您可以通过替换上面的代码轻松地将它们添加到数组中

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

更接近

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

我希望有所帮助。