简体   繁体   English

无法从Android设备连接到Google Cloud端点

[英]Can't connect to google cloud endpoint from android device

I am learning to work with google cloud endpoint. 我正在学习使用Google Cloud Endpoint。 I am trying to connect from my device however, I keep getting an error. 我正在尝试从设备进行连接,但是我一直收到错误消息。

failed to connect to /192.168.1.100 (port 8080) after 20000ms: isConnected failed: ECONNREFUSED (Connection refused) 20000毫秒后无法连接到/192.168.1.100(端口8080):isConnected失败:ECONNREFUSED(连接被拒绝)

How do I overcome this issue, I would like to run on a real device? 我要如何在实际设备上运行,如何克服此问题?

Get Jokes.class 获取笑话课

public class GetJokes extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;

@Override
protected String doInBackground(Pair<Context, String>... params) {
    if (myApiService == null) {  // Only do this once
        MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
            new AndroidJsonFactory(), null)
            // options for running against local devappserver
            // - 10.0.2.2 is localhost's IP address in Android emulator
            // - turn off compression when running against local devappserver
            .setRootUrl("http://10.0.2.2:8080/_ah/api/")
            .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                @Override
                public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                    abstractGoogleClientRequest.setDisableGZipContent(true);
                }
            });
        // end options for devappserver

        myApiService = builder.build();
    }

    context = params[0].first;
    String name = params[0].second;

    try {
        return myApiService.sayHi(name).execute().getData();
    } catch (IOException e) {
        return e.getMessage();
    }
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    Log.i("Failed to con", result);
}
}

MainActivityFragment.class MainActivityFragment.class

public class MainActivityFragment extends Fragment {

public static final String JOKE = "JOKE";

public MainActivityFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_main, container, false);

    Button tellJokeButton = (Button)root.findViewById(R.id.tellJoke_button);
    tellJokeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new GetJokes().execute(new Pair<Context, String>(getActivity(), "Manfred"));
        }
    });

    AdView mAdView = (AdView) root.findViewById(R.id.adView);
    // Create an ad request. Check logcat output for the hashed device ID to
    // get test ads on a physical device. e.g.
    // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    mAdView.loadAd(adRequest);
    return root;
}

public void tellJoke(){

    Intent intent = new Intent(getActivity(), JokeTellerActivity.class);
    //TODO: get jokes from Google Cloud endpoint
    intent.putExtra(JOKE,

        getActivity().getString(R.string.joke)
    );

    startActivity(intent);
}
}

MyEndPoint.class MyEndPoint.class

public class MyEndpoint {

public static List<Joke> mJokes = new ArrayList<>();

/** A simple endpoint method that takes a name and says Hi back */
@ApiMethod(name = "sayHi")
public MyBean sayHi(@Named("name") String name) {
    MyBean response = new MyBean();
    response.setData("Hi, " + name);

    return response;
}
}

I've tried running it on several different devices and none of them would connect. 我试过在几种不同的设备上运行它,但没有一个可以连接。

I've had the same problem because I'm also doing this project from the Android Nanodegree (Udacity). 我遇到了同样的问题,因为我也在Android Nanodegree(Udacity)进行此项目。

I've found the solution in this question . 我已经找到了这个问题的解决方案。 Because the answers there are a bit messy or uncomplete, I'm going to explain in detail what I did to run the local server on my computer and test it with a real device. 因为答案有些混乱或不完整,所以我将详细解释在计算机上运行本地服务器并使用真实设备对其进行测试时所执行的操作。

1) Add httpAddress = "0.0.0.0" to the appengine block in your build.gradle file of the backend (Google Cloud Endpoint) module, like this: 1)将httpAddress = "0.0.0.0"添加到后端(Google Cloud Endpoint)模块的build.gradle文件中的appengine块中,如下所示:

appengine {
    ...
    httpAddress = "0.0.0.0"
}

According to a comment on the linked question this means that 'will accept from anywhere'. 根据对链接问题的评论,这意味着“将在任何地方接受”。

2) Run your backend module locally (ie. start the web server). 2)在本地运行后端模块(即,启动Web服务器)。 This is trivial: select the backend configuration on the drop-down menu and press the green button. 这很简单:在下拉菜单中选择后端配置,然后按绿色按钮。 You can find more detailed instructions here . 您可以在此处找到更详细的说明

You should now be able to open a browser (on your computer) and navigate to http://localhost:8080/ and see a webpage with 'Hello, Endpoints!' 现在,您应该能够打开浏览器(在计算机上)并导航到http://localhost:8080/并看到带有“ Hello,Endpoints!”的网页。 and many other stuff. 还有很多其他的东西。

3) Find your computer's IP address (on a Mac go to System Preferences -> Network) and then set it as the root url in your Android app code, like this: 3)找到您计算机的IP地址(在Mac上,转到“系统偏好设置”->“网络”),然后将其设置为Android应用程序代码中的根网址,如下所示:

MyApi.Builder builder = new MyApi.Builder(
                            AndroidHttp.newCompatibleTransport(),
                            new AndroidJsonFactory(), 
                            null
).setRootUrl("http://192.168.1.36:8080/_ah/api/")

That's all! 就这样!

So you've setup an AppEngine based cloud endpoint as a local development server on the same machine in which you are running an Android emulator? 因此,您已将基于AppEngine的云终结点设置为运行Android模拟器的同一台计算机上的本地开发服务器? Be sure you're using the correct IP address (and port) for the endpoint. 确保您为端点使用了正确的IP地址(和端口)。 The local IP address you need is not the one in use by the Android emulator, but the host dev machine. 您需要的本地IP地址不是 Android仿真器所使用的本地IP地址,而是主机dev计算机。 For example: 例如:

Local Dev Machine: 192.168.1.100 本地开发机:192.168.1.100

AppEngine server on dev machine: listening on 8080 开发人员机器上的AppEngine服务器:在8080上侦听

Android Emulator running on dev machine: 10.0.2.2 在开发机上运行的Android模拟器:10.0.2.2

You should be able to access the API explorer on the dev machine via a browser on the Android emulator as well. 您还应该能够通过Android模拟器上的浏览器访问开发机上的API资源管理器。 You can use that to sanity check that your app is using the correct address: 您可以使用它来检查您的应用使用的是正确的地址:

http://192.168.1.100:8080/_ah/api/explorer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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