使用协议缓冲区的Android Http请求和响应

时间:2013-11-18 11:47:26

标签: android protocol-buffers

我是协议缓冲区主题的新手。 但我知道json解析和所有这些 现在我实际上正在使用这个协议缓冲区我正在制作一个Http请求和使用带有协议缓冲区的响应的应用程序。

我正在使用android中的协议缓冲区创建一个登录页面。

服务中的一切工作都会返回我想要的每个字段的响应 服务给我的信息那些不同然后响应实际来自服务器。

我有关于.proto文件的协议缓冲区的基本知识和用于从proto编译java文件的工具,所有的连接也已完成,我的需要只是响应或如何序列化和Deserislize响应消息。

**AuthenticateUserRequest.Builder abr = AuthenticateUserRequest
                    .newBuilder();
            abr.setUserID(p_UserName);
            abr.setPassword(p_Password);

            URL url = new URL(
                    "http://10.0.2.2:49847/Services");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // ResCode = conn.getResponseCode();
            // URLConnection conn = url.openConnection();

            conn.setRequestProperty("content-type", "application/x-protobuf");
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            abr.build().writeTo(os);
            os.flush();
            os.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            byte[] result = String.valueOf(sb).getBytes();
            AuthenticateUserResponse.parseFrom(result).toBuilder();**

多数人的代码可以帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:4)

您的问题是您正在尝试将编码的protobuf响应视为文本。 Protocol Buffers是一种二进制序列化格式。如果您将二进制数据转换为String,或者如果您尝试使用Reader将其读取,则该数据将被损坏。

要解决此问题,请替换代码的整个第二部分 - 从您创建BufferedReader的行开始 - 使用此代码:

AuthenticateUserResponse response =
    AuthenticateUserResponse.parseFrom(conn.getInputStream());

答案 1 :(得分:0)

我不知道是否能回答你的问题,但这是我的代码。

我已经使用过这两个类了。

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class HttpClientSingleton {

    private static final int JSON_CONNECTION_TIMEOUT = 30000;
    private static final int JSON_SOCKET_TIMEOUT = 50000;
    private static HttpClientSingleton instance;
    private HttpParams httpParameters ;
    private DefaultHttpClient httpclient;

    private void setTimeOut(HttpParams params){
     HttpConnectionParams.setConnectionTimeout(params, JSON_CONNECTION_TIMEOUT);
     HttpConnectionParams.setSoTimeout(params, JSON_SOCKET_TIMEOUT);
    }

    private HttpClientSingleton() {
     httpParameters = new BasicHttpParams();
     setTimeOut(httpParameters);
     httpclient = new DefaultHttpClient(httpParameters);
    }

    public static DefaultHttpClient getHttpClientInstace(){
     if(instance==null)
         instance = new HttpClientSingleton();
     return instance.httpclient;
    }
}


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import android.util.Log;

public class WSClient {

        public final String get(String url) {

                String resultCode = "";
                String result = "";

                HttpGet httpget = new HttpGet(url);
                HttpResponse response;

                try {
                        Log.i("WSClient Get taxi", "Url -> " + url);
                        response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
                        HttpEntity entity = response.getEntity();

                        if (entity != null) {
                                //Código da respostas
                                resultCode = String.valueOf(response.getStatusLine().getStatusCode());
                                InputStream instream = entity.getContent();
                                //Resposta
                                result = toString(instream);
                                instream.close();
                                Log.i("WSClient if entity not null taxi", "Result Code " + resultCode);
                                Log.i("WSClient if entity not null taxi", "Result: " + result);

                                if(!resultCode.equals("200"))                                        
                                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                        }
                } catch (Exception e) {
                        Log.i("Exception WSClient get taxi", "Exception ->" + e);
                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                }
                return result;
        }

        public final String post(String url, String json) {
                String resultCode = "";
                String result = "";
                try {
                        HttpPost httpPost = new HttpPost(new URI(url));
                        httpPost.setHeader("Content-type", "application/json");
                        StringEntity sEntity = new StringEntity(json, "UTF-8");
                        httpPost.setEntity(sEntity);

                        HttpResponse response;
                        response = HttpClientSingleton.getHttpClientInstace().execute(httpPost);
                        HttpEntity entity = response.getEntity();

                        if (entity != null) {
                                resultCode = String.valueOf(response.getStatusLine().getStatusCode());
                                InputStream instream = entity.getContent();
                                result = toString(instream);
                                instream.close();

                                if(!resultCode.equals("200"))                                        
                                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                        }

                } catch (Exception e) {
                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                }
                return result;
        }

        public final String put(String url, String json) {

                String resultCode = "";
                String result = "";

                try {

                        HttpPut httput = new HttpPut(url);
                        httput.setHeader("Content-type", "application/json");
                        StringEntity sEntity = new StringEntity(json, "UTF-8");
                        httput.setEntity(sEntity);

                        HttpResponse response;
                        response = HttpClientSingleton.getHttpClientInstace().execute(httput);
                        HttpEntity entity = response.getEntity();

                        if (entity != null) {
                                resultCode = String.valueOf(response.getStatusLine().getStatusCode());
                                InputStream instream = entity.getContent();
                                result = toString(instream);
                                instream.close();

                                if(!resultCode.equals("200"))                                        
                                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                        }
                } catch (Exception e) {
                        result = "{\"errorCode\": 1, \"descricao\": \"Falha de rede!\"}";
                }
                return result;
        }

        private String toString(InputStream is) throws IOException {

                byte[] bytes = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int lidos;
                while ((lidos = is.read(bytes)) > 0) {
                        baos.write(bytes, 0, lidos);
                }
                return new String(baos.toByteArray());
        }
}