2015-09-30 6 views
0

Я использую Apache HttpClient для размещения/получения настраиваемого объекта с использованием API REST. Ниже приведен пример кода. Мой метод putObject() работает отлично, и я мог бы сериализовать объект Person и правильно помещать его. Тем не менее, при получении объекта, я получил ниже ошибки:Apache HttpClient - REST API: проблема при преобразовании ответа на настраиваемый объект, который помещается как SerializableEntity

Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to Person at MyTest.demoGetRESTAPI(MyTest.java:88) at MyTest.main(MyTest.java:21) 

КАЖЕТСЯ код для создания объекта Person из объекта ответа не является правильным

HttpEntity httpEntity = response.getEntity(); 
      byte[] resultByteArray = EntityUtils.toByteArray(httpEntity); 
      Person person = (Person)SerializationUtils.deserialize(resultByteArray); 

Могу ли я делать Somthing неправильно при получении байт [] массив и преобразование в объект Person. Пожалуйста, помогите мне решить эту проблему.

Полный пример программы:

import java.io.Serializable; 

import org.apache.commons.lang.SerializationUtils; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPut; 
import org.apache.http.entity.SerializableEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

public class MyTest { 

    public static void main(String[] args) throws Exception { 

     putObject(); 

     getObject(); 
    } 

    public static void putObject() throws Exception 
    { 
     HttpClient httpClient = new DefaultHttpClient(); 

     Person person = new Person(); 
     person.setName("Narendra"); 
     person.setId("1"); 

     try 
     { 
      //Define a postRequest request 
      HttpPut putRequest = new HttpPut("http://localhost:9084/ehcache-server/rest/screeningInstance/2221"); 

      //Set the API media type in http content-type header 
      putRequest.addHeader("content-type", "application/x-java-serialized-object"); 

      //Set the request put body 
      SerializableEntity personSEntity = new SerializableEntity(SerializationUtils.serialize(person)); 
      putRequest.setEntity(personSEntity); 

      //Send the request; It will immediately return the response in HttpResponse object if any 
      HttpResponse response = httpClient.execute(putRequest); 

      //verify the valid error code first 
      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode != 201) 
      { 
       throw new RuntimeException("Failed with HTTP error code : " + statusCode); 
      } 
     } 
     finally 
     { 
      //Important: Close the connect 
      httpClient.getConnectionManager().shutdown(); 
     } 
    } 

    public static void getObject() throws Exception 
    { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     try 
     { 
      //Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also. 
      //Choice depends on type of method you will be invoking. 
      HttpGet getRequest = new HttpGet("http://localhost:9084/ehcache-server/rest/screeningInstance/2221"); 

      //Set the API media type in http accept header 
      getRequest.addHeader("accept", "application/x-java-serialized-object"); 

      //Send the request; It will immediately return the response in HttpResponse object 
      HttpResponse response = httpClient.execute(getRequest); 

      //verify the valid error code first 
      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode != 200) 
      { 
       throw new RuntimeException("Failed with HTTP error code : " + statusCode); 
      } 

      //Now pull back the response object 

      HttpEntity httpEntity = response.getEntity(); 
      byte[] resultByteArray = EntityUtils.toByteArray(httpEntity); 
      Person person = (Person)SerializationUtils.deserialize(resultByteArray);   
     } 
     finally 
     { 
      //Important: Close the connect 
      httpClient.getConnectionManager().shutdown(); 
     } 
    } 

} 

class Person implements Serializable{ 
    String name; 
    String id; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    @Override 
    public String toString() { 
     return "Person [name=" + name + ", id=" + id + "]"; 
    } 


} 

ответ

1

Я получил решение. Это было ошибкой в ​​моем коде:

При помещении объекта, я написал ниже код. Это было сделано за два раза. Сначала от объекта Person до байта [], а второй от байта [] до байта [].

SerializableEntity personSEntity = new SerializableEntity(SerializationUtils.serialize(person)); 
      putRequest.setEntity(personSEntity); 

Это правильный подход:

SerializableEntity personSEntity = new SerializableEntity(person); 
      putRequest.setEntity(personSEntity); 

После получения двоичного файла с REST, код должен быть, как показано ниже, чтобы получить объект:

HttpEntity httpEntity = response.getEntity(); 
InputStream inputStream = null; 
try { 
     inputStream = httpEntity.getContent(); 
     Person p = (Person) SerializationUtils.deserialize(inputStream); 
     System.out.println("Person:" + p.getName()); 
    } 
    finally { 
     inputStream.close(); 
    } 

Это работало как CHARM !!

 Смежные вопросы

  • Нет связанных вопросов^_^