HttpClient将手机上的数据发送到服务器

 到官网下载jar包,下载GA发布版本即可

在项目中将httpclient-4.5.5.jar、httpcore-4.4.9.jar、httpmime-4.5.5.jar三个jar包放进lib中

封装一个发送请求的类

package com.autumn.tools;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClient {
    public static void main(String[] args) throws IOException {
        post("使用HttpClient发送数据");
    }

    public static void post(String data) throws IOException {
        //实例化httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建post实例
        HttpPost httpPost = new HttpPost("http://www.***.***:80/****g/HttpInfoController/getAndroid");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

        //添加参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("data", data));

        //将参数放入post实例
        httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

        //httpclient执行发送操作返回response
        CloseableHttpResponse response = httpclient.execute(httpPost);

        // 返回
        try {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);

            System.out.println("返回状态"+response.getStatusLine());
            System.out.println("返回内容:"+result);

            EntityUtils.consume(entity);
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            //关闭response
            response.close();
        }
    }
}

消息通知发送到服务器代码

package com.example.bookandroid;

import com.autumn.tools.HttpClient;

import android.app.Notification;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import android.util.Log;

/**
 * 消息监听
 * @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();
        // 获取接收消息的抬头
        String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
        // 获取接收消息的内容
        String notificationText = extras.getString(Notification.EXTRA_TEXT);
        HttpClient.post("Notification posted 通知标题: "+notificationTitle+"通知内容:"+notificationText);  //将消息通知发送到服务器
        Log.i("XSL_Test", "Notification posted " + 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.i("XSL_Test", "Notification removed " + notificationTitle + " & " + notificationText);
    }
    
}

服务器端

@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";
    }
}

猜你喜欢

转载自www.cnblogs.com/aeolian/p/9283784.html