I am working on android for the first time, I just want to connect my android app with node server on a button click. my node server is
在localhost上运行,我的手机也连接到同一个 网络。有没有可能连接我的Android应用程序与运行 节点服务器。我要做的就是调用只有服务器的路由 打印" Hello world"在console.log的服务器中。 如果可能请帮我解释一下代码。 感谢。
**This is my ooClick function in android.**
public void sendMessage(View view) {
name = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
phone = (EditText)findViewById(R.id.phone);
address = (EditText)findViewById(R.id.address);
try {
String nme = URLEncoder.encode(name.getText().toString(), "UTF-8");
String eMail = URLEncoder.encode(email.getText().toString(), "UTF-8");
String ph = URLEncoder.encode(phone.getText().toString(), "UTF-8");
String add = URLEncoder.encode(address.getText().toString(), "UTF-8");
// Create http client object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://192.168.0.183:3000/save?text1="+nme+"&text2="+eMail+"&text3="+ph+"&text4="+add;
//Toast.makeText(getBaseContext(),"Please wait, connecting to server."+URL,Toast.LENGTH_LONG).show();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
//content.setText(SetServerString);
Toast.makeText(getBaseContext(),"response"+SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"fail",Toast.LENGTH_LONG).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(),"response",Toast.LENGTH_LONG).show();
}
**This is my function in node server**
app.get('/save', function(req, res){
var text1= req.param('text1');
var text2= req.param('text2');
var text3= req.param('text3');
var text4= req.param('text4');
console.log(text1+' '+text2+' '+text3);
});
我只想在控制台中打印文本。
答案 0 :(得分:0)
您应该考虑使用Retrofit库。这使得从Android应用程序进行HTTP调用变得非常容易。此外,您还需要外部IP地址或服务器名称才能通过网络访问数据。 &#34;本地主机&#34;始终指的是运行软件的当前计算机。对于您的桌面,&#34; localhost&#34;是桌面;对于您的Android设备,&#34; localhost&#34;是Android设备。