gpt4 book ai didi

java - 连接到本地 Web 服务的 Android 模拟器

转载 作者:行者123 更新时间:2023-12-01 15:52:24 26 4
gpt4 key购买 nike

大家好,我的机器上设置了一个本地 Web 服务,它是使用 JPA 在 netbeans 中构建的 Web 服务。我也将它本地连接到 mySQL 服务器。我同时连接了数据库和网络服务。 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;
}

主类

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

最佳答案

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

这里有一个更好的 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;
}
}

}

}

关于java - 连接到本地 Web 服务的 Android 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5743267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com