Java Android Emulator连接到本地Web服务
大家好,我的机器上安装了一个本地web服务,它是一个使用JPA在netbeans中构建的web服务。我还让它在本地连接到mySQL服务器。我已经连接了数据库和web服务。Web服务可以显示XML/JSON。我的问题是让android仿真器使用来自web服务的JSON。我们正在使用的URL是“http://10.0.2.2:8080/Web4/resources/hotel2s/“这应该允许仿真器连接到web服务,对吗?当我尝试启动和使用模拟器时,它会崩溃。下面是一些源代码。我们确信它应该读入并用GSON等进行解析,但我们不确定它是否正在连接 结果类Java Android Emulator连接到本地Web服务,java,android,service,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服务,对吗?当我尝试启动和使用模拟器时,它会崩溃。下面是一些源代码。我们确信它应该读入并用
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;
}
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;
}
}
酒店响应等级
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;
}
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;
}
}
public class hotel\u响应
{
公共列表酒店结果;
公共字符串查询;
}
主类
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;
}
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;
}
}
public类connectRest扩展活动
{
//我们在这里也尝试了Reg的机器ip,它也使用了不同的ip,模拟器连接到它是正确的吗?
字符串url=”http://10.0.2.2:8080/Web4/resources/hotel2s/";
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputStream source=retrieveStream(url);//url中的流
Gson Gson=new Gson();//Gson对象
Reader Reader=新的InputStreamReader(源);//在流中读取
hotel_Response Response=gson.fromJson(reader,hotel_Response.class);//填写hotel_Response类中的变量
Toast.makeText(this,response.query,Toast.LENGTH_SHORT).show();
列出hotelresults=response.hotelresults;
对于(酒店结果酒店结果:hotelresults)
{
Toast.makeText(这个,hotel_Result.hotelName,Toast.LENGTH_SHORT.show();
}
}
私有InputStream retrieveStream(字符串url)
{
DefaultHttpClient=新的DefaultHttpClient();
HttpGet getRequest=新的HttpGet(url);
试一试{
HttpResponse getResponse=client.execute(getRequest);
final int statusCode=getResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC\u OK)
{
Log.w(getClass().getSimpleName(),“Error”+statusCode+”表示URL+URL);
返回null;
}
HttpEntity getResponseEntity=getResponse.getEntity();
返回getResponseEntity.getContent();
}
捕获(IOE异常)
{
getRequest.abort();
Log.w(getClass().getSimpleName(),“URL错误”+URL,e);
}
返回null;
}
}
确保您的清单中有“允许internet访问”权限
这里有一个更好的try-catch实现,它在一个AsyncTask()中完成工作,以使UI线程保持愉快:)可以在Java代码极客()上找到原始文章,但它缺少我的改进
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;
}
}
}
}
import java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.Reader;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入android.app.Activity;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.Toast;
导入com.google.gson.gson;
导入com.javacodegeks.android.json.model.Result;
导入com.javacodegeeks.android.json.model.SearchResponse;
公共类JsonParsingActivity扩展活动{
私有静态最终字符串url=”http://search.twitter.com/search.json?q=javacodegeeks";
受保护的InitTask\u InitTask;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
按钮按钮=(按钮)findViewById(R.id.button1);
setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
_initTask=新的initTask();
_执行(getApplicationContext());
}
});
}
@凌驾
公共void onStop(){
super.onStop();
_initTask.cancel(true);
}
受保护类InitTask扩展了AsyncTask
{
@凌驾
受保护的SearchResponse doInBackground(上下文…参数)
{
InputStream源=检索流(url);
SearchResponse=null;
如果(源!=null){
Gson Gson=新的Gson();
Reader Reader=新的InputStreamReader(源);
试一试{
response=gson.fromJson(reader,SearchResponse.class);
发布进度(response.query);
reader.close();
}捕获(例外e){
Log.w(getClass().getSimpleName(),“错误:”+e.getMessage()+“用于URL”+URL);
}
}
如果(!this.isCancelled()){
返回响应;
}否则{
返回null;
}
}
@凌驾
受保护的void onProgressUpdate(字符串…s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(),s[0],Toast.LENGTH_SHORT).show();
}
@凌驾
受保护的void onPostExecute(SearchResponse响应)
{
super.onPostExecute(响应);
StringBuilder=新的StringBuilder();
if(响应!=null){
字符串delim=“*”;
列表结果=response.results;
对于(结果:结果){
builder.append(