Я не могу отправить параметры моего запроса в bluemix, развернутый node.js

Я не могу получить ответ от развернутого bluemix node.js. Мой код android xml, java и код node.js приведен ниже. Может ли кто-нибудь помочь мне в решении этой проблемы.

Мой xml-код для Android:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context="com.example.rest.MainActivity" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_centerInParent="true"
    android:orientation="vertical" >      

    <TextView
        android:id="@+id/textreg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:paddingLeft="20dp"
        android:text="Register here"
        android:textAlignment="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0b84aa"
        android:textSize="25sp"
        android:typeface="serif" />

    <EditText
        android:id="@+id/editTextreg5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:ems="10"
        android:hint="Full Name"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editTextreg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:ems="10"
        android:hint="Short Id   @ibm.com"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textEmailAddress" />




    <EditText
        android:id="@+id/editTextreg2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Password"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:textColor="#000000"
        android:textSize="20dp"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonreg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_marginTop="20dp"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:textColor="#0b84aa"
        android:textStyle="bold"
        android:text="Register" />

</LinearLayout>

And My java code:

package com.example.rest;
        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;

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



       import org.json.JSONObject;
      import org.json.JSONException;
       import com.loopj.android.http.AsyncHttpClient;
       import com.loopj.android.http.JsonHttpResponseHandler;
       import com.loopj.android.http.RequestParams;
        import org.apache.http.Header;
     import android.support.v7.app.ActionBarActivity;
      import android.app.ProgressDialog;
     import android.content.Intent;
      import android.os.Bundle;
        import android.util.Log;
       import android.view.Menu;
     import android.view.MenuItem;
     import android.view.View;
    import android.widget.Button;
     import android.widget.EditText;
      import android.widget.TextView;
    import android.widget.Toast;

     public class MainActivity extends ActionBarActivity {


    String url = "http://mobilefeedbackform.mybluemix.net/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button breg1 = (Button) findViewById(R.id.buttonreg);

        breg1.setOnClickListener(new View.OnClickListener() {



            public void onClick(View v) {

                final EditText Name =(EditText) findViewById(R.id.editTextreg5);
                final EditText Email =(EditText) findViewById(R.id.editTextreg);
                final EditText Passwd =(EditText) findViewById(R.id.editTextreg2);

                if(Name.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter Name", Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                else if(Email.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter EmailId", Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                else if(Passwd.getText().toString().length()==0)
                {
                    Toast.makeText(MainActivity.this,
                            "Please enter Password", Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                else
                {
                    String result = null;
                    String nametxt = Name.getText().toString();
                    String emailtxt = Email.getText().toString();
                    String passwdtxt = Passwd.getText().toString();

                  //this is the route of your Node.js service on Bluemix
                    //String yourNodeJsBluemixRoute = "mobilefeedbackform.mybluemix.net";//http://mobilefeedbackform.mybluemix.net/
                    String url = "http://mobilefeedbackform.mybluemix.net/";
                    // These are just example strings, you can use your own here
                    Toast.makeText(MainActivity.this,
                            "Before sending "+ nametxt + emailtxt + passwdtxt, Toast.LENGTH_LONG)
                            .show();
                    // Create necessary objects
                    HttpClient httpClient = new DefaultHttpClient();

                    try
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside try ", Toast.LENGTH_LONG)
                                .show();
                        //httpResponse = http.get(RESTSERVICEURI + "/?deviceid=" + deviceId + "&latitude=" + String.valueOf(gps.getLatitude()) + "&longitude=" + String.valueOf(gps.getLongitude())); 
                    HttpGet httpGet = new HttpGet(url+"?name=" + nametxt + "&email=" + emailtxt + "&passwd=" + passwdtxt);
                    Toast.makeText(MainActivity.this,
                            "After sending ", Toast.LENGTH_LONG)
                            .show();
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    Toast.makeText(MainActivity.this,
                            "Got response ", Toast.LENGTH_LONG)
                            .show();
                    if (httpEntity != null)
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside If ", Toast.LENGTH_LONG)
                                .show();
                    InputStream inputstream = httpEntity.getContent();
                    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream));
                    StringBuilder stringbuilder = new StringBuilder();

                    String currentline = null;
                    while ((currentline = bufferedreader.readLine()) != null)
                    {
                        Toast.makeText(MainActivity.this,
                                "Inside while ", Toast.LENGTH_LONG)
                                .show();
                    stringbuilder.append(currentline + "\n");
                    }

                    result = stringbuilder.toString();
                    inputstream.close();
                    }

                    return;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        }
                }
            }
            });
    }
}

и мой код node.js:

 var express    = require('express');
app         = express();



var http = require('http');
var url = require('url');

  var PORT = (process.env.VCAP_APP_PORT || 8000);
 var HOST = (process.env.VCAP_APP_HOST || 'localhost');

 var queryData = null;

  http.createServer(function(request, response) {
  queryData = url.parse(request.url, true).query;
   console.log("Hai3");
  //respond to the client
   response.write("Got the GET request");
   response.end();
   }).listen(PORT, HOST);

Может ли кто-нибудь помочь мне в этом вопросе?


person Santhosh S    schedule 22.04.2015    source источник
comment
Am not able to retrieve response. Ответ пустой? Нет ответа? Разве это не то, что вы ожидали? Будьте немного более многословны.   -  person Huey    schedule 22.04.2015
comment
Да, я не уверен насчет пустого или нулевого значения, но я не вижу никакого ответа от node.js на моем экране Android. Я могу видеть его после отправки всплывающего уведомления на моем экране. Он не выполняет HttpResponse httpResponse = httpClient.execute (httpПолучить);   -  person Santhosh S    schedule 22.04.2015
comment
Не могли бы вы попробовать сделать запросы к своему приложению за пределами вашего приложения для Android, чтобы попытаться изолировать проблему?   -  person Jeff Sloyer    schedule 23.04.2015
comment
Как только я нажму на свой URL-адрес маршрута Bluemix, я могу получить ответ от node.js и отобразить Got the Get request в браузере. но это не работает на устройстве Android   -  person Santhosh S    schedule 23.04.2015


Ответы (2)


В вашем коде Node.js вы должны использовать request.query. Это вернет объект вашей строки запроса в виде пары ключ-значение.

person Jeff Sloyer    schedule 20.07.2015

В качестве альтернативы вы можете использовать Mobile Cloud SDK для отправки запросов REST на ваш сервер Node в Bluemix.

Android SDK был разработан таким образом, что каждый API возвращает задачу Bolts. Это поможет вам понять ваши ответы Node с гораздо меньшими трудностями.

person Dave Cariello    schedule 27.04.2015