Android Emulator连接到本地Web服务

时间:2011-04-21 11:09:53

标签: java android service

大家好我在我的机器上设置了本地Web服务,它是一个使用JPA在netbeans中构建的Web服务。我也将它本地连接到mySQL服务器。我有数据库和Web服务连接。 Web服务可以显示XML / JSON。我的问题是让Android模拟器从Web服务中使用JSON。我们使用的URL是“http://10.0.2.2:8080/Web4/resources/hotel2s/”这应该允许模拟器连接到Web服务我是否正确?当我尝试启动并消耗模拟器崩溃时。这是一些源代码。我们确信它应该读入并解析GSON等,但我们不确定它是否连接。

结果类

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

酒店回复类

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

2 个答案:

答案 0 :(得分:1)

确保您的清单中有允许的互联网访问权限。

这是一个更好的try-catch实现,它在AsyncTask()中工作以保持UI线程的快乐:)原始文章可以在Java Code Geeks(http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html)上找到,但它缺乏我的改进!

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

    }

}

答案 1 :(得分:0)

这是上面代码的完整try-catch实现。我先实现了这个,然后意识到我真正需要知道的是通过/失败。无论如何,可能会帮助某人。再次,道具转到Java Code Geeks让我开始...... 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;
        }

    }

}