android设置打印机wifi(OKHttp+firefox的插件:HttpRequester+WireShake + servlet)

来源:互联网 发布:淘宝家居排行榜 编辑:程序博客网 时间:2024/06/06 20:12

android设置打印机wifi(OKHttp+firefox的插件:HttpRequester+WireShake + servlet)。post和put提交。

通过android手机设置打印机的wifi步骤(爬虫):

  • 1.通过chrome捕获按钮所提交的请求数据
  • 2.通过WireShark捕获所提交的请求数据
  • 3.通过HttpRequester模拟浏览器提交请求数据
  • 4.引用OkHttp实现模拟浏览器提交请求数据
  • 5.(可不看)通过servlet查看post和put请求的数据

步骤1、2(先post后put):

下面图的都是‘点击应用提交的是post请求’的截图(即打开打印机的wifi开关):

这里写图片描述

这里写图片描述

这里写图片描述

由于上图的chrome找不到post的表单数据,所以借助WireShark抓包
这里写图片描述
这里写图片描述

下面的图是通过put方式提交wifi的账号和密码给服务器(这里的服务器指的是打印机)截图:

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

步骤3(HttpRequester插件模拟浏览器提交post和put请求)

HttpRequester插件提交post请求来打开打印机的wifi开关

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

HttpRequester插件提交put请求来提交wifi账号和密码

这里写图片描述

这里写图片描述

步骤4

1.导包

compile 'com.squareup.okhttp3:okhttp:3.9.0'

2.java实现

import java.io.IOException;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/** * Created by shixing on 2017/11/1. */public class NetworkSetting {    private static final OkHttpClient mOkHttpClient = new OkHttpClient();    private static final String URL_POST = "http://192.168.223.1/hp/device/config_result_YesNo.html/config";    private static final String URL_PUT = "http://192.168.223.1/IoMgmt/Adapters/wifi0/Profiles/Active";    static final MediaType XML = MediaType.parse("application/xml");    //打开wifi开关    public static String postData() {        FormBody.Builder formBodyBuilder = new FormBody.Builder();        formBodyBuilder.add("Clear", "\346\230\257");        formBodyBuilder.add("Menu", "NetWifiChange");        formBodyBuilder.add("Configuration", "WifiEnabled=1");        RequestBody requestBody = formBodyBuilder.build();        Request request = new Request.Builder()                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")                .addHeader("Accept-Encoding", "gzip, deflate")                .addHeader("Accept-Language", "zh-CN,zh;q=0.8")                .addHeader("Cache-Control", "max-age=0")                .addHeader("Connection", "keep-alive")                .addHeader("Content-Type", "application/x-www-form-urlencoded")                .addHeader("Host", "192.168.223.1")                .addHeader("Origin", "http://192.168.223.1")                .addHeader("Referer", "http://192.168.223.1/hp/device/config_result_YesNo.html?tab=Networking&amp;menu=NetWifiChange&amp;WifiEnabled=1")                .addHeader("Upgrade-Insecure-Requests", "1")                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")                .url(URL_POST)                .post(requestBody)                .build();        try {            Response response = mOkHttpClient.newCall(request).execute();            Log.d(MainActivity.TAG, "postData: " + response.code());            return response.body().string();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return null;    }    //把用户名和密码以一个xml字符串的形式put到打印机(这里的打印机就是服务器)上    public static String putMyData() {        RequestBody requestBody = RequestBody.create(XML,getXml());        Request request = new Request.Builder().url(URL_PUT)                .addHeader("Accept","application/xml, text/xml, */*")                .addHeader("Accept-Encoding","gzip, deflate")                .addHeader("Connection","keep-alive")                .addHeader("Accept-Language","zh-CN,zh;q=0.8")                .addHeader("Host","192.168.223.1")                .addHeader("Origin","http://192.168.223.1")                .addHeader("Referer","http://192.168.223.1/set_config_network_Wireless.html?tab=Networking&menu=NetWireless")                .addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")                .addHeader("X-Requested-With","XMLHttpRequest")                .put(requestBody).build();        try {            Response response = mOkHttpClient.newCall(request).execute();            Log.d(MainActivity.TAG, "putMyData: " + response.code());            return response.body().string();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    private static String getXml() {        return "<?xml version:\"1.0\" encoding=\"UTF-8\" ?><io:Profile  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dd=\"http://www.hp.com/schemas/imaging/con/dictionaries/1.0/\" xmlns:io=\"http://www.hp.com/schemas/imaging/con/ledm/iomgmt/2008/11/30\" xmlns:wifi=\"http://www.hp.com/schemas/imaging/con/wifi/2009/06/26\" xmlns:ipdyn=\"http://www.hp.com/schemas/imaging/con/ledm/internalprintdyn/2008/03/21\" ><io:AdapterProfile><io:WifiProfile><wifi:SSID>646C696E6B</wifi:SSID> <wifi:CommunicationMode>infrastructure</wifi:CommunicationMode> <wifi:EncryptionType>WPA_PSK</wifi:EncryptionType><wifi:AuthenticationMode>WPA_PSK</wifi:AuthenticationMode><io:KeyInfo><io:WpaPassPhraseInfo><wifi:RsnEncryption>AESOrTKIP</wifi:RsnEncryption><wifi:RsnAuthorization>autoWPA</wifi:RsnAuthorization><wifi:PassPhrase>6E686C323230323230</wifi:PassPhrase></io:WpaPassPhraseInfo></io:KeyInfo></io:WifiProfile></io:AdapterProfile></io:Profile>";    }}

MainActivity.java(不要在ui线程访问网络)

public class MainActivity extends AppCompatActivity {    public static final String TAG = "MainActivity";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        new Thread() {            @Override            public void run() {                Log.d(TAG, "run: " + NetworkSetting.postData());                Log.d(TAG, "run: " + NetworkSetting.putMyData());            }        }.start();    }}

步骤5 (通过servlet查看post和put请求的数据)

1.把client端的URL_POST改为:

private static String URL_POST = "http://localhost:8080/TestForm/FormServlet";

2.servlet代码

import java.io.BufferedReader;import java.io.IOException;import java.util.Enumeration;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class FormServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("get");        doPost(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("post");        System.out.println("content-length:" + req.getContentLength());        System.out.println("......................");        Enumeration<String> attrs = req.getAttributeNames();        String strAttr = "attributes:";        while(attrs.hasMoreElements()) {            strAttr = strAttr + attrs.nextElement() + ", ";        }        System.out.println(strAttr);        System.out.println("......................");        Enumeration<String> names = req.getHeaderNames();        String strName = "attribute names:";        while(names.hasMoreElements()) {            String headName = names.nextElement();            strName = strName + headName+ ":" + req.getHeader(headName) + ", ";        }        System.out.println(strName);        System.out.println("......................");        System.out.println("authType:" + req.getAuthType() + ", characterEncoding:" + req.getCharacterEncoding()                +", contentType:" + req.getContentType() + ", queryString:" + req.getQueryString());        System.out.println("......................");        Enumeration<String> params = req.getParameterNames();        String strParamNames = "params names:";        while(params.hasMoreElements()) {            strParamNames = strParamNames + params.nextElement() + ", ";        }        System.out.println("......................");        System.out.println(strParamNames);        System.out.println("......................");        Map<String, String[]> paramsMaps = req.getParameterMap();        for(String key : paramsMaps.keySet()) {            String [] values = paramsMaps.get(key);            String strVal = "";            for(String str: values) {                strVal = strVal + str + ", ";            }            System.out.println("key=" + key +", values=" + strVal);        }        BufferedReader br = req.getReader();        System.out.println("======================");        System.out.println("bufferReader:");        String str = "";        while((str = br.readLine()) != null) {            System.out.println(str);        }        resp.sendRedirect(req.getContextPath()+"/haha.html");    }    @Override    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        super.doPut(req, resp);        System.out.println("put");        System.out.println("content-length:" + req.getContentLength());        System.out.println("......................");        Enumeration<String> attrs = req.getAttributeNames();        String strAttr = "attributes:";        while(attrs.hasMoreElements()) {            strAttr = strAttr + attrs.nextElement() + ", ";        }        System.out.println(strAttr);        System.out.println("......................");        Enumeration<String> names = req.getHeaderNames();        String strName = "attribute names:";        while(names.hasMoreElements()) {            String headName = names.nextElement();            strName = strName + headName+ ":" + req.getHeader(headName) + ", ";        }        System.out.println(strName);        System.out.println("......................");        System.out.println("authType:" + req.getAuthType() + ", characterEncoding:" + req.getCharacterEncoding()                +", contentType:" + req.getContentType() + ", queryString:" + req.getQueryString());        System.out.println("......................");        Enumeration<String> params = req.getParameterNames();        String strParamNames = "params names:";        while(params.hasMoreElements()) {            strParamNames = strParamNames + params.nextElement() + ", ";        }        System.out.println("......................");        System.out.println(strParamNames);        System.out.println("......................");        Map<String, String[]> paramsMaps = req.getParameterMap();        for(String key : paramsMaps.keySet()) {            String [] values = paramsMaps.get(key);            String strVal = "";            for(String str: values) {                strVal = strVal + str + ", ";            }            System.out.println("key=" + key +", values=" + strVal);        }        BufferedReader br = req.getReader();        System.out.println("======================");        System.out.println("bufferReader:");        String str = "";        while((str = br.readLine()) != null) {            System.out.println(str);        }        resp.sendRedirect(req.getContextPath()+"/haha.html");    }}

服务器收到的post请求数据如下:

postcontent-length:73......................attributes:......................attribute names:accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8, accept-encoding:gzip, deflate, accept-language:zh-CN,zh;q=0.8, cache-control:max-age=0, connection:keep-alive, host:192.168.223.1, origin:http://192.168.223.1, referer:http://192.168.223.1/hp/device/config_result_YesNo.html?tab=Networking&amp;menu=NetWifiChange&amp;WifiEnabled=1, upgrade-insecure-requests:1, user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36, content-type:application/x-www-form-urlencoded, content-length:73, ......................authType:null, characterEncoding:null, contentType:application/x-www-form-urlencoded, queryString:null............................................params names:Clear, Menu, Configuration, ......................key=Clear, values=是, key=Menu, values=NetWifiChange, key=Configuration, values=WifiEnabled=1, ======================bufferReader:

服务器收到的put请求数据如下:

putcontent-length:916......................attributes:......................attribute names:accept:application/xml, text/xml, */*, accept-encoding:gzip, deflate, connection:keep-alive, accept-language:zh-CN,zh;q=0.8, host:192.168.223.1, origin:http://192.168.223.1, referer:http://192.168.223.1/set_config_network_Wireless.html?tab=Networking&menu=NetWireless, user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36, x-requested-with:XMLHttpRequest, content-type:application/xml, content-length:916, ......................authType:null, characterEncoding:null, contentType:application/xml, queryString:null............................................params names:......................======================bufferReader:<?xml version:"1.0" encoding="UTF-8" ?><io:Profile  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dd="http://www.hp.com/schemas/imaging/con/dictionaries/1.0/" xmlns:io="http://www.hp.com/schemas/imaging/con/ledm/iomgmt/2008/11/30" xmlns:wifi="http://www.hp.com/schemas/imaging/con/wifi/2009/06/26" xmlns:ipdyn="http://www.hp.com/schemas/imaging/con/ledm/internalprintdyn/2008/03/21" ><io:AdapterProfile><io:WifiProfile><wifi:SSID>646C696E6B</wifi:SSID> <wifi:CommunicationMode>infrastructure</wifi:CommunicationMode> <wifi:EncryptionType>WPA_PSK</wifi:EncryptionType><wifi:AuthenticationMode>WPA_PSK</wifi:AuthenticationMode><io:KeyInfo><io:WpaPassPhraseInfo><wifi:RsnEncryption>AESOrTKIP</wifi:RsnEncryption><wifi:RsnAuthorization>autoWPA</wifi:RsnAuthorization><wifi:PassPhrase>6E686C323230323230</wifi:PassPhrase></io:WpaPassPhraseInfo></io:KeyInfo></io:WifiProfile></io:AdapterProfile></io:Profile>

结论:

从服务器收到的post和put的请求数据对比得出,put的xml字符串通过req.getReader()来读取,而post提交的表单则通过

Map<String, String[]> paramsMaps = req.getParameterMap();        for(String key : paramsMaps.keySet()) {            String [] values = paramsMaps.get(key);            String strVal = "";            for(String str: values) {                strVal = strVal + str + ", ";            }            System.out.println("key=" + key +", values=" + strVal);        }

来获取。