HttpClient将手机上的数据发送到服务器
到官网下载jar包,下载GA发布版本即可
在项目中将httpclient-4.5.5.jar、httpcore-4.4.9.jar、httpmime-4.5.5.jar、commons-logging-1.2.jar四个jar包放进lib中
服务器端
@Controller
@RequestMapping("/HttpInfoController")
public class GetHttpInfoController {
@RequestMapping("/getAndroid")
@ResponseBody
public String getAndroid(HttpServletRequest request, HttpServletResponse response) {
String data = request.getParameter("data");
try
{
String path="/root/Android.log";
File file=new File(path);
//若不存在即创建文件
if(!file.exists())
file.createNewFile(); //创建文件输入流
FileOutputStream out=new FileOutputStream(file,true); //如果追加方式用true StringBuffer sb=new StringBuffer();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sb.append("-----------"+sdf.format(new Date())+"------------\n");
sb.append(data+"\n");
//写入
out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
out.close();
}
catch(IOException ex)
{
System.out.println(ex.getStackTrace());
return "success";
}finally { }
return "success";
}
}
移动端
发送请求工具类
package com.autumn.tools; import android.icu.util.Output;
import android.util.Log; import com.autumn.pojo.GPSPojo; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class HttpClientUtil {
public static void main(String[] args) throws IOException,
KeyManagementException, NoSuchAlgorithmException {
//post(URL,"Android项目HttpClient手动发送post()");
//postAndroid(URL,"Android项目HttpClient手动发送postAndroid()");
GPSPojo gpsPojo = new GPSPojo();
gpsPojo.setUserId("qyid1");
gpsPojo.setUserName("autumn");
postObjectAndroid(URL,gpsPojo);
}
//通用记录到日志url
public static String URL = "http://*****/getAndroid";
public static String URL_LOGIN = "http://***/forAndroid";
/**
* 正常环境中使用
* @param data
*/
public static void post(String url,String data) {
// 实例化httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建post实例
if(url==null||url.isEmpty()){
url = URL;
}
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); // 添加参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", data)); CloseableHttpResponse response = null;
// 将参数放入post实例
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// httpclient执行操作返回response
response = httpclient.execute(httpPost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* 安卓使用放入data:json格式的对象
* @param data
*/
public static void postAndroid(final String url,final String data) {
Runnable runnable = new Runnable() {
public void run() { // 实例化httpclient
// CloseableHttpClient httpclient = HttpClients.createDefault(); 使用会与android核心包起冲突
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
// 创建post实例
HttpPost httpPost = null;
if(url==null||url.isEmpty()){
httpPost = new HttpPost(URL);
}else{
httpPost = new HttpPost(url);
}
httpPost.setHeader("Content-type",
"application/x-www-form-urlencoded"); // 添加参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data", data)); // CloseableHttpResponse response = null; 使用会与android核心包起冲突
HttpResponse response = null;
// 将参数放入post实例
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = httpclient.execute(httpPost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
} /**
* 安卓使用放Http发送Object对象中的每一个字段作为参数,值作为参数值
* @param data
*/
public static void postObjectAndroid(final String url,final Object data) {
Runnable runnable = new Runnable() {
public void run() { // 实例化httpclient
// CloseableHttpClient httpclient = HttpClients.createDefault(); 使用会与android核心包起冲突
org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
// 创建post实例
HttpPost httpPost = null;
if(url==null||url.isEmpty()){
httpPost = new HttpPost(URL);
}else{
httpPost = new HttpPost(url);
}
httpPost.setHeader("Content-type",
"application/x-www-form-urlencoded"); // 添加参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
Class dataClass = data.getClass();
Field[] declaredFields = dataClass.getDeclaredFields();
for (Field field:declaredFields){
try {
field.setAccessible(true);
if(field.get(data)!=null){ //字段值不为null,则作为参数
params.add(new BasicNameValuePair(field.getName(),field.get(data).toString()));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
//params.add(new BasicNameValuePair("data", data)); // CloseableHttpResponse response = null; 使用会与android核心包起冲突
HttpResponse response = null;
// 将参数放入post实例
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {//如果返回成功则解析
HttpEntity responseEntity = response.getEntity();
//方法一
InputStream inputStream = responseEntity.getContent();
StringBuilder stringBuilder = new StringBuilder();
byte[] temp = new byte[1024];
OutputStream outputStream = new ByteArrayOutputStream();
int len =0;
while((len=inputStream.read(temp))!=-1){
outputStream.write(temp,0,len);
String result = new String(temp);
stringBuilder.append(result);
}
Log.i("stringBuilder",stringBuilder.toString());
//方法二
/*String str = EntityUtils.toString(responseEntity, HTTP.UTF_8);
Log.i("str",str);*/ }
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
} }
消息通知监听ListenerService
package com.autumn.service; import android.app.Notification;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import com.autumn.tools.HttpClientUtil; /**
* 消息监听
* @author Autumn
*/
public class NotificationMonitorService extends android.service.notification.NotificationListenerService {
// 在收到消息时触发
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// TODO Auto-generated method stub
Bundle extras = sbn.getNotification().extras;
// 获取接收消息APP的包名
String notificationPkg = sbn.getPackageName();
// 获取接收消息的抬头
final String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
// 获取接收消息的内容
String notificationText = extras.getString(Notification.EXTRA_TEXT);
if(notificationTitle==null&¬ificationText==null){ //如果为空,则不执行
return;
}
//发送数据
HttpClientUtil.postAndroid("autumn app: "+notificationPkg+" title: " + notificationTitle + " & " + notificationText);
//Log.e("listener_post", "autumn app post: "+notificationPkg+" title: " + notificationTitle + " & " + notificationText);
} // 在删除消息时触发
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
// TODO Auto-generated method stub
Bundle extras = sbn.getNotification().extras;
// 获取接收消息APP的包名
String notificationPkg = sbn.getPackageName();
// 获取接收消息的抬头
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
// 获取接收消息的内容
String notificationText = extras.getString(Notification.EXTRA_TEXT);
//Log.e("listener_remove", "autumn app post: "+notificationPkg+" title: " + notificationTitle + " & " + notificationText);
} }
要在AndroidManifest.xml注册service和权限
<!-- 访问网络,发送数据需要上网 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- application中注册消息监听service -->
<service android:name="com.autumn.service.NotificationMonitorService" <!--这里写service所在位置,默认包用.,不是默认包要写全路径,与activity同包可以只写类名-->
android:label="NotificationMonitor"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
启动监听服务分两种方式,一个是跳到授权界面并启动服务,第二个直接启动服务
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent); //授权,跳到授权界面并启动服务
Intent startIntent = new Intent(this, BackService.class);
startService(startIntent); //启动服务
然后在MainActivity.java中添加运行service,onCreate()方法中代码
Intent intent_listener=new Intent(this, NotificationMonitorService.class);
intent_listener.setAction("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startService(intent_listener); //启动监听后台服务 setContentView(R.layout.activity_main); //获取启动服务按钮
Button btn_getAcc = (Button) findViewById(R.id.bt1);
//按钮点击事件
btn_getAcc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String string = Settings.Secure.getString(getContentResolver(),
"enabled_notification_listeners");
if (!string.contains(NotificationMonitorService.class.getName())) {
Toast.makeText(MainActivity.this, "未获得权限,请选择允许权限", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "已经获得权限", Toast.LENGTH_SHORT).show();
} Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);// 来授权 会跳到授权界面
}
});
软件自启
软件开关机自启广播
package com.autumn.receiver; import com.autumn.service.NotificationMonitorService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; /**
* 软件自启代码
* @author Autumn
*/
public class BroReceiver extends BroadcastReceiver {
public BroReceiver() {
} @Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent intent1=new Intent(context, NotificationMonitorService.class);
intent1.setAction("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
context.startService(intent1); //启动监听服务
}
}
}
AndroidManifest.xml中注册
<!--开机权限-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <!-- 自启 -->
<receiver
android:name="com.autumn.receiver.BroReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
服务器查看接受数据 tail -f Android.log

注意事项:
1.httpclient出现和system/framework中的jar包起冲突情况
这是由于使用了CloseableHttpClient造成的,把
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpclient.execute(httpRequest);
替换成
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
2.主线程中不可以存在http请求,要另起线程
Runnable runnable = new Runnable() {
public void run() {
HttpClient.postAndroid("Notification posted 通知标题: " + "通知内容:");
}
};
new Thread(runnable).start();
3.本人用的MIUI9系统,会出现每次点进去都要选择权限等一系列问题解决方案如下。
1.设置->更多设置->系统安全->通知使用权
2.软件设为自启动
HttpClient将手机上的数据发送到服务器的更多相关文章
- 使用Fiddler抓取手机上的数据包
在IIS中,如果网站已经绑定了域名在使用IP是不能访问的,需要添加一个空的主机名与IP的映射才能访问.如下图: Fiddler抓取手机包 在PC上建一个WIFI热的 勾选Fiddler中Tool-&g ...
- Android使用OpenGL ES2.0显示YUV,您的手机上的数据要解决两个方面的坐标
如果说 ,我不知道,如果你不明白这个话题.连接到:http://blog.csdn.net/wangchenggggdn/article/details/8896453(下称链接①), 里面评论有非常 ...
- VC++ Post 方法 上传数据到web服务器
最近在做一个项目,需要与WEB服务器交互一些信息.其中一项就是文件的上传与下载.现来一个上传的代码 #include "stdio.h" #include "WinSoc ...
- [PHP]利用XAMPP搭建本地服务器, 然后利用iOS客户端上传数据到本地服务器中(三. PHP端代码实现)
一.安装XAMPP http://www.cnblogs.com/lidongxu/p/5256330.html 二. 配置MySql http://www.cnblogs.com/lidongx ...
- 如何在 Android 手机上实现抓包?
如何在 Android 手机上实现抓包? http://www.zhihu.com/question/20467503 我想知道某个应用究竟在数据提交到哪里,提交了什么.网上的教程太复杂,不想麻烦.有 ...
- 史上最全最强Charles截取手机https协议数据包教程(附上利用此技术制作最近微信比较火的头脑王者辅助外挂)!
纯原创,思路也是本人花了半个小时整理出来的,整个完成花费了本人半天时间,由于不才刚大学毕业,所以有的编码方面可能不入大牛们的眼,敬请原谅!如有转载请附上本地址,谢谢! 最近微信朋友圈刚刚被跳一跳血洗, ...
- Android 本地tomcat服务器接收处理手机上传的数据之案例演示
上一篇:Android 本地tomcat服务器接收处理手机上传的数据之环境搭建 本篇基于上一篇搭建的服务器端环境,具体介绍Android真机上传数据到tomcat服务器的交互过程 场景:A ...
- UiPath工具取得网页上面的数据,写入到csv,Outlook邮件发送
问题描述: 想取得网页上面的股票价格,之后写入到csv文本里面之后添加附件发送邮件. 解决方法: 利用UIPath工具来取得数据,之后写入再发送. 具体步骤: 1.打开网页,之后找到所显示的股票行情的 ...
- 把采集到的数据发送到一个Google Docs或者Google Form上 这个网站提供了参考和例子
把采集到的数据发送到一个Google Docs或者Google Form上这个网站提供了参考和例子 http://www.instructables.com/id/Post-to-Google-Doc ...
随机推荐
- Oracle数据类型number
oracle数值类型只有number number(变长) 1.number可以存放整数,可以存放小数: 2.number(p,s) 说明: p表示有效位,s为小数位:范围p[1,38],s[-84, ...
- 解决Ubuntu14.04下vi编辑器不能使用方向键和退格键问题
参考:http://blog.sina.com.cn/s/blog_7d0c2fed01010zbi.html 系统:Ubuntu14.04 使用vi命令时,不能正常编辑文件,使用方向键时老是出现很多 ...
- as modern frameworks have warmed people to the idea of using builder-type patterns and anonymous inner classes for such things
mybatis – MyBatis 3 | SQL语句构建器 http://www.mybatis.org/mybatis-3/zh/statement-builders.html SqlBuilde ...
- Django - 常用配置
一.logging配置 Django项目常用的logging配置 settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': F ...
- Network of Schools---poj1236(强连通分量)
题目链接 题意:学校有一些单向网络,现在需要传一些文件 求:1,求最少需要向几个学校分发文件才能让每个学校都收到, 2,需要添加几条网络才能从任意一个学校分发都可以传遍所有学校. 解题思路(参考大神的 ...
- Spring 小知识
1:Advice环绕通知相当于 aop:before之类的 2:Mybatis执行流程: Configuration对象时运行项目时,就直接生成了. 2.1 通过XMLBuilder 解析XML, ...
- Spark Core (一) 什么是RDD的Transformation和Action以及Dependency(转载)
1. Spark的RDD RDD(Resilient Distributed Datasets),弹性分布式数据集,是对分布式数据集的一种抽象. RDD所具备5个主要特性: 一组分区列表 计算每一个数 ...
- 鸟哥linux私房菜学习笔记,U盘安装centos5.3不能正常进入图形界面的问题
前面说过自己成功引导了centos系统,现在进入启动界面,首次进入会进行相关设置,按照步骤一步一步完成,取消完光盘安装,点击下一步,就进入下面这个界面,没有登录框...没错!怎么蓝屏了,这可是linu ...
- Web前台学习总结
前台的技术有很多种,流行的框架也是枚不胜举,在这里我们只讨论html,css,js这些基本的技术,相信大家如果掌握了这些最基本的技术,其他的技术也就会使用了. 下面是一个案例的形式来讲解上述的技术. ...
- 005-matlab2018a安装破解
1.下载地址: 百度云下载链接:https://pan.baidu.com/s/1uTYAxVX1_Hx6nbsgf4W4kA 密码:asrw 官网下载地址: 2.解压. 3.双击setup.exe后 ...