官网下载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&&notificationText==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将手机上的数据发送到服务器的更多相关文章

  1. 使用Fiddler抓取手机上的数据包

    在IIS中,如果网站已经绑定了域名在使用IP是不能访问的,需要添加一个空的主机名与IP的映射才能访问.如下图: Fiddler抓取手机包 在PC上建一个WIFI热的 勾选Fiddler中Tool-&g ...

  2. Android使用OpenGL ES2.0显示YUV,您的手机上的数据要解决两个方面的坐标

    如果说 ,我不知道,如果你不明白这个话题.连接到:http://blog.csdn.net/wangchenggggdn/article/details/8896453(下称链接①), 里面评论有非常 ...

  3. VC++ Post 方法 上传数据到web服务器

    最近在做一个项目,需要与WEB服务器交互一些信息.其中一项就是文件的上传与下载.现来一个上传的代码 #include "stdio.h" #include "WinSoc ...

  4. [PHP]利用XAMPP搭建本地服务器, 然后利用iOS客户端上传数据到本地服务器中(三. PHP端代码实现)

    一.安装XAMPP   http://www.cnblogs.com/lidongxu/p/5256330.html 二. 配置MySql http://www.cnblogs.com/lidongx ...

  5. 如何在 Android 手机上实现抓包?

    如何在 Android 手机上实现抓包? http://www.zhihu.com/question/20467503 我想知道某个应用究竟在数据提交到哪里,提交了什么.网上的教程太复杂,不想麻烦.有 ...

  6. 史上最全最强Charles截取手机https协议数据包教程(附上利用此技术制作最近微信比较火的头脑王者辅助外挂)!

    纯原创,思路也是本人花了半个小时整理出来的,整个完成花费了本人半天时间,由于不才刚大学毕业,所以有的编码方面可能不入大牛们的眼,敬请原谅!如有转载请附上本地址,谢谢! 最近微信朋友圈刚刚被跳一跳血洗, ...

  7. Android 本地tomcat服务器接收处理手机上传的数据之案例演示

    上一篇:Android 本地tomcat服务器接收处理手机上传的数据之环境搭建     本篇基于上一篇搭建的服务器端环境,具体介绍Android真机上传数据到tomcat服务器的交互过程   场景:A ...

  8. UiPath工具取得网页上面的数据,写入到csv,Outlook邮件发送

    问题描述: 想取得网页上面的股票价格,之后写入到csv文本里面之后添加附件发送邮件. 解决方法: 利用UIPath工具来取得数据,之后写入再发送. 具体步骤: 1.打开网页,之后找到所显示的股票行情的 ...

  9. 把采集到的数据发送到一个Google Docs或者Google Form上 这个网站提供了参考和例子

    把采集到的数据发送到一个Google Docs或者Google Form上这个网站提供了参考和例子 http://www.instructables.com/id/Post-to-Google-Doc ...

随机推荐

  1. 热词统计以及Quartz.net的简单使用

    一.热词统计 方案一: 设计一个表:ID       KeyWord     Count 当用户再输入框中查询的时候,我们就往表中插入数据,在插入之前首先判断是否已经存在keyword,存在的话,让C ...

  2. OpenPGP协议的一个JavaScript实现:OpenPGP.js

    OpenPGP.js 是OpenPGP协议的一个Javascript实现. 基于 JavaScript的OpenPGP实现方便用户可以直接在浏览器中加密和解密Web邮件,不需要专门的邮件客户端.

  3. PhotoSwipe中文API(四)

    在幻灯片自定义HTML内容 为了使PhotoSwipe显示HTML内容的幻灯片,你需要在幻灯片对象定义html属性.它应该包含HTML字符串或DOM元素对象. var items = [ // sli ...

  4. PAT 1088 Rational Arithmetic[模拟分数的加减乘除][难]

    1088 Rational Arithmetic(20 分) For two rational numbers, your task is to implement the basic arithme ...

  5. java构建树用的Node

    package org.ccnt.med.body; import java.util.ArrayList; import java.util.List; public class Node { // ...

  6. adb shell top 命令

    原文地址https://blog.csdn.net/kittyboy0001/article/details/38562515 原文地址https://blog.csdn.net/u010503912 ...

  7. 在GUI程序中使用控制台的两种方法

    win32程序启用控制台(控制台文件名:conout$,conin$,conerr$) //添加控制台,加入在程序构造函数中 AllocConsole(); freopen("conin$& ...

  8. Linux系统——Inotify事件监控工具

    每秒传输文件200个 Rsync放在定时任务中也只是一分钟执行一回,要想达到实时的效果,为防止单点nfs架构故障,再启动一台nfs服务器作为主nfs服务器的备份服务器,此时需要inotify实时同步数 ...

  9. #C++初学记录(高精度运算)(加法)

    高精度运算 不管是int还是double亦或者long long ,这些定义变量都有数据范围的一定限制,在计算位数超过十几位的数,也就是超过他们自身的数据范围时,不能采用现有类型进行计算,只能自己通过 ...

  10. 883. Projection Area of 3D Shapes

    问题 NxN个格子中,用1x1x1的立方体堆叠,grid[i][j]表示坐标格上堆叠的立方体个数,求三视图面积. Input: [[1,2],[3,4]] Output: 17 Explanation ...