Android向node.js编写的服务器发送数据并接收请求
作者:GISuuser 发布时间:2022-10-12 02:08:21
标签:Android,node.js,服务器
本文实例为大家分享了Android向node.js服务器发送数据并接收请求的具体代码,供大家参考,具体内容如下
首先时node.js服务器端代码
var http = require("http");
var fs = require("fs");
var queryString = require('querystring');
var url = require('url');
var util = require('util');
http.createServer(function (request, response) {
// 定义了一个post变量,用于暂存请求体的信息
var post = '';
request.on('data', function(chunk){
post += chunk;
});
// 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
request.on('end', function(){
post = queryString.parse(post);
console.log("请求结束"+post.body);
response.writeHead(200, {"Content-Type": "text/plain;charset=utf8"});
response.write("请求成功");
response.end();
});
}).listen(8888);
console.log("服务器启动");
function writeFile(str) {
fs.writeFile('E:/log.txt', str, function (err) {
if (err) {
return console.error(err);
}
console.log("数据写入成功!");
})
}
然后是Android部分
package com.example.hanbo.servertest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView);
Button button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setText("开始请求");
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL("http://192.168.1.177:8888");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setRequestProperty("Content-Type","application/json");
OutputStream outputStream=connection.getOutputStream();
BufferedWriter requestBody=new BufferedWriter(new OutputStreamWriter(outputStream));
String str = URLEncoder.encode("抓哇", "UTF-8");
requestBody.write("name=javaPost&body=1");
requestBody.flush();
requestBody.close();
getResponseJava(connection);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
private void getResponseJava(HttpURLConnection urlConnection) {
InputStream in = null;
try {
in = urlConnection.getInputStream();//响应
} catch (IOException e) {
urlConnection.disconnect();
//textView.setText(e.getMessage());
return;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
final StringBuilder result = new StringBuilder();
String tmp = null;
try {
while((tmp = reader.readLine()) != null){
result.append(tmp);
}
} catch (IOException e) {
//textView.setText(e.getMessage());
return;
} finally {
try {
reader.close();
urlConnection.disconnect();
} catch (IOException e) {
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(result);
}
});
}
}
最后是结果图:
来源:http://blog.csdn.net/gisuuser/article/details/77748779


猜你喜欢
- 在项目中有使用到延时队列的场景,做个简单的记录说明;首先DelayQueue实现了BlockingQueue,加入其中的元素必须实现Dela
- 首先介绍下JSON的定义,JSON是JavaScript Object Notation的缩写。一种轻量级的数据交换格式,具有良好的可读和便
- 时间戳在游戏开发中虽然是一个比较小的功能?但是如果缺少这个功能就会导致开发遇到困难,为了帮助大家开发,下面就给大家介绍下将时间戳的使用方法,
- 问题之前项目能够正常运行,因为默认选择db0,后来新的需求来了,不是默认db0,而是给参数选择db。修改后代码如下,却报错NOAUTH Au
- 本文为大家分享了java interface的两个经典用法,供大家参考,具体内容如下1.Java多态接口动态加载实例编写一个通用程序,用来计
- 一、介绍1、"Lambda表达式"是一个特殊的匿名函数,简化了匿名委托的使用,是一种高效的类似于函数式编程的表达式,La
- 很多的Android入门程序猿来说对于Android自定义View,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义Vie
- public class MainActivity extends Activity { TextView tv; Ch
- LiveData概述LiveData 是一种可观察的数据存储器类: 与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循
- 网络基础知识1、OSI分层模型和TCP/IP分层模型的对应关系这里对于7层模型不展开来讲,只选择跟这次系列主题相关的知识点介绍。2、七层模型
- 在Spring中进行事务管理非常简单,只需要在方法上加上注解@Transactional,Spring就可以自动帮我们进行事务的开启、提交、
- (鼠标放上去将一直显示,移开动画继续),提供normal和error两种边框。介绍:传统的确定,取消,OK,CANCAL之类的对话框太繁琐了
- 序列帧动画经常用到,最直接的方式就是用Animation录制。但某些情况下这种方式并不是太友好,需要靠代码的方式进行序列帧动画的实现。代码实
- 本文实例为大家分享了C#字数统计(字母、数字、汉字、符号)的具体代码,供大家参考,具体内容如下namespace 测试1{ public p
- 一维数组1.一维数组的定义方式:int[] array1 = new int[3];//声明创建一个包含3个元素的数组array1(初始值为
- 前言在阅读本篇文章时请关注如下问题:1.什么是三层架构?2.为什么使用三层架构?3.三层与以往使用的两层相比有什么不同?它的优势在哪里?4.
- 本文实例为大家分享了Android实现图像切换器的具体代码,供大家参考,具体内容如下java代码:private int[] imageId
- 一、前言闭锁与栅栏是在多线程编程中的概念,因为在多线程中,我们不能控制线程的执行状态,所以给线程加锁,让其按照我们的想法有秩序的执行。闭锁C
- 在Activity 添加即可getWindow().addFlags(WindowManager.LayoutParams.FLAG_SEC
- 一、安装JDK、SDK、NDK无论是用C#和VS2015开发Androd App还是用Java和Eclipse开发Androd App,都需