简体   繁体   中英

Android Emulator connecting to Local Web service

Hi all I have a local web service set up on my machine, it is a web service which was built in netbeans using the JPA. I have it connecting locally to a mySQL server also. I have both the database and web service connecting. The webservice can display XML/JSON. My problem is getting the android emulator to consume the JSON from the web service. The URL we are using is "http://10.0.2.2:8080/Web4/resources/hotel2s/" this should allow the emulator to connect to the web service am I correct? When I try to launch and consume the emulator crashes. Here is some source code. We are sure that it should read in and parse with GSON etc but we are not sure if it is connecting or not.

RESULT CLASS

public class hotel_Result 
{
    @SerializedName("hotelAddress")
    protected String hotelAddress;
    @SerializedName("HotelDescription")
    protected String hotelDescription;
    @SerializedName("hotelName")
    protected String hotelName;
    @SerializedName("hotelRating")
    protected int hotelRating;
}

HOTEL RESPONSE CLASS

public class hotel_Response
{
public List<hotel_Result> hotelresults;
public String query;
}

MAIN CLASS

public class connectRest extends Activity 

{
    // We tried Reg's machines ip here as well and it crashed also used different ips is this correct for the emulator to connect to it?
    String url = "http://10.0.2.2:8080/Web4/resources/hotel2s/";

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        InputStream source = retrieveStream(url); // Stream in the URL

        Gson gson = new Gson(); // GSON object

        Reader reader = new InputStreamReader(source); // Read in the stream

        hotel_Response response = gson.fromJson(reader,hotel_Response.class); // Fill in the variables in the class hotel_response

        Toast.makeText(this,response.query,Toast.LENGTH_SHORT).show();

        List<hotel_Result> hotelresults = response.hotelresults;


        for(hotel_Result hotel_Result : hotelresults)
        {
            Toast.makeText(this,hotel_Result.hotelName,Toast.LENGTH_SHORT).show();
        }
    }   

    private InputStream retrieveStream(String url)
    {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);

        try{
            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();

            if(statusCode != HttpStatus.SC_OK)
            {
                Log.w(getClass().getSimpleName(),"Error" + statusCode + " for URL " + url);
                return null;
            }
            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();
        }
        catch(IOException e)
        {
            getRequest.abort();
            Log.w(getClass().getSimpleName(),"Error for URL " + url, e);
        }
        return null;
    }
}

Make sure you have the allow internet access permission in your manifest.

Here's a better try-catch implementation and it does the work in an AsyncTask() to keep the UI thread happy :) The original article can be found on Java Code Geeks ( http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html ) but it lacks my improvements!

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;

public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params ) 
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                    reader.close();
                } catch (Exception e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s) 
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response ) 
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient(); 
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                HttpResponse getResponse = client.execute(getRequest);
                HttpEntity getResponseEntity = getResponse.getEntity();
                return getResponseEntity.getContent();
            } catch (Exception e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                return null;
            }
        }

    }

}

Here's a full try-catch implementation of the code above. I implemented this first and then realized all I really needed to know was pass/fail. Anyway, might help someone. Again, props go to Java Code Geeks for getting me started ... Android JSON Parsing with GSON Tutorial

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;

public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params ) 
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                } catch (JsonSyntaxException e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url); 
                    return null;
                } catch (JsonIOException e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                    return null;
                } finally {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                    }
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s) 
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response ) 
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient(); 
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                try {
                    HttpResponse getResponse = client.execute(getRequest);
                    final int statusCode = getResponse.getStatusLine().getStatusCode();
                    if (statusCode != HttpStatus.SC_OK) { 
                        Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); 
                        return null;
                    }
                    HttpEntity getResponseEntity = getResponse.getEntity();
                    try {
                        return getResponseEntity.getContent();
                    } catch (IllegalStateException e) {
                        getRequest.abort();
                        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                        return null;
                    } catch (IOException e) {
                        getRequest.abort();
                        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                        return null;
                    }
                } catch (ClientProtocolException e) {
                    getRequest.abort();
                    Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                } catch (IOException e) {
                    getRequest.abort();
                    Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                }
            } catch (IllegalArgumentException e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
            }
            return null;
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM