Meddyy Thakkarr
Meddyy Thakkarr

Reputation: 61

Android Http request and response using protocol buffer

I am very new for the protocol buffer topic. but i know the json parsing and all about that For now i am actually working on this protocol buffer i am making one application which Http request and Response using android with protocol buffer.

I am making one login page with the use of protocol buffer in android.

Everything is working wall from the service returns the response every field which i want but the information which services are giving me thats Different then response which is actually coming from server.

i have the basic knowledge of protocol buffer about .proto file and tools for compiling the java file from proto and all the connectivity is also done, my need is only response or how to serialize and Deserislize the response message.

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

Thats the code of my anyone can help me to resolve this.

Thanks in advance.

Upvotes: 4

Views: 4040

Answers (2)

Kenton Varda
Kenton Varda

Reputation: 45326

Your problem is that you're trying to treat the encoded protobuf response as text. Protocol Buffers is a binary serialization format. If you convert binary data to String, or if you try to read it with a Reader, it will be corrupted.

To fix the problem, replace the whole second part of your code -- starting from the line where you created the BufferedReader -- with this:

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

Upvotes: 4

Bruno Pinto
Bruno Pinto

Reputation: 2013

I don't know if that answer your question, but here is my code.

I've used these 2 class.

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

Upvotes: 0

Related Questions