How to send Jsonobject to a Web Service?

Asked

Viewed 5,778 times

3

I am trying for the first time to consume a Web Service in my Android application by sending data by JSON format.

To accomplish the task I have a class to make the connection.

public class ConexaoHttpJson {

public static JSONObject enviarSolicitacao(String urlPost,JSONObject obj) throws ClientProtocolException, IOException, JSONException {      

    HttpContext localContext = new BasicHttpContext();
    HttpClient client = new DefaultHttpClient();  
    HttpPost post = new HttpPost(urlPost); 
    post.setHeader("Content-type", "application/json");
    //post.setHeader("Authorization",token);
    //post.setHeader("Cookie","ASP.NET_SessionId="+sessao+"; path=/; HttpOnly");

    post.setEntity(new StringEntity(obj.toString()));
    HttpResponse response = client.execute(post,localContext);  

    HttpEntity entity = response.getEntity();
    InputStream instream = entity.getContent();

    String resultString= convertStreamToString(instream);

    JSONObject jsonObjRecv = new JSONObject(resultString);

    Log.i("json servidor", jsonObjRecv.toString());
    instream.close();

    return  jsonObjRecv;
}

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }           
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {               
            e.printStackTrace();            
        }
    }
    return sb.toString();
}
}

Now I need HTML and ObjectJson, in which I am creating in a class Activity, in that format:

    public void onClickConnect(View view) {
        new Thread() {
            @Override
            public void run() {
            super.run();
            try {                       
                 JSONObject json = new JSONObject();
                 json.put("email", login.getText().toString()); 
                 json.put("password", senha.getText().toString());

                 String url = "http://webservice.com/Api.php?user=logar";//EXEMPLO
                 JSONObject response = ConexaoHttpJson.enviarSolicitacao(url, json);                           
                 } catch (ClientProtocolException e) {
                     e.printStackTrace();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } catch (JSONException e) {
                     e.printStackTrace();
                 }
            }
        }.start();   
    }

I want to send a URL, and email and password in JSON format, pick up the answer from Webservice and work on it.

The problem is in the method line enviarSolicitação.

   String resultString= convertStreamToString(instream);        
   JSONObject jsonObjRecv = new JSONObject(resultString);

Error log

05-13 22:48:25.430: W/System.err(1951): org.json.JSONException: Value <meta of type java.lang.String cannot be converted to JSONObject
05-13 22:48:25.430: W/System.err(1951):     at org.json.JSON.typeMismatch(JSON.java:111)
05-13 22:48:25.430: W/System.err(1951):     at org.json.JSONObject.<init>(JSONObject.java:158)
05-13 22:48:25.430: W/System.err(1951):     at org.json.JSONObject.<init>(JSONObject.java:171)
05-13 22:48:25.430: W/System.err(1951):     at com.sostudy.ConexaoHttpJson.enviarSolicitacao(ConexaoHttpJson.java:44)
05-13 22:48:25.430: W/System.err(1951):     at com.sostudy.MainActivity$1.run(MainActivity.java:153)
  • Raul, on which line did the error occur? And what is the error? :)

  • When I use Debug it stops on the line: json.put("email", login.getText().toString());

  • 1

    login.getText() by chance is not returning null?

  • Really this was occurring, I put fixed values in the fields, now I saw that I have some problem in sending methodSolicitation, I will try to find out the problem, thanks.

  • Or did login is null?

  • I changed the question, the issue of login null I fixed, the insertion of the values in the various login and password was taking place outside the correct time.

  • Could you post the reply string? It seems to me that this has more to do with JSON’s response formatting or encoding error than the implementation you did.

  • 1

    @Raulpires, if possible post the contents of the variable resultString, which is return, I believe that the return string of the web service is not in the correct format, to convert to the JSON object, so the org.json.JSONException.

  • Hi guys, thank you so much for your attention. It was error in the return of Webservice. It was returning an entire HTML. I’d like to close the question, but I can’t seem to do that here :)

Show 4 more comments

2 answers

2

To use this code line, the value of resultString has to be a valid JSON.

JSONObject jsonObjRecv = new JSONObject(resultString) 

A JSON is an object per key, value where the key has to be a string and the value can be one string, a number, a Boolean (true or false), a JSON object or a array of string.

Probably your resultString is not a valid Json.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.