charles本身带有DNS Spoofing Settings的功能,在Tools菜单里,使用这个,就不需要在搭配其他Host修改工具使用了,我们项目中,开发时需要频繁改host,这个功能对我来说十分有用。
但是charles自带的这个功能,只能导入charles本身导出的xml配置,不能直接导入host文件,很不方便,我看了下这个xml的格式,自己写了个工具来转化格式,可以把host转化为charles支持的xml格式来导入。代码下面贴出来,并附上下载链接。
执行下面的命令运行即可,后面的hosts/参数,表示需要转化的host目录或文件名
java -jar convertFromHostToCharlesDnsSpoofingXml.jar hosts/
代码如下,非常简单,一看就懂。
package com.example.java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class MyClass {
public static void main(String... args) throws IOException {
if (args == null || args.length == 0) {
System.out.print("error! no argument! Please enter a file or directory path");
return;
}
File inputFile = new File(args[0]);
if (!inputFile.exists()) {
System.out.print(args[0] + "is not a file path");
return;
}
boolean mkdir = new File("charlesHosts").mkdir();
if (inputFile.isDirectory()) {
File[] files = inputFile.listFiles();
if (files == null) {
System.out.print("empty directory!");
return;
}
for (File file : files) {
convert(file);
}
} else {
convert(inputFile);
}
}
private static void convert(File file) throws IOException {
dnsSpoofing dnsSpoofing = new dnsSpoofing();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
line = line.replaceAll("[\uFEFF-\uFFFF]", "");
if (line.startsWith("#")) continue;
if (line.isEmpty()) continue;
String[] split = line.split("\\s+");
dnsSpoof dnsSpoof = new dnsSpoof();
dnsSpoof.address = split[0];
if (split.length < 2) {
System.out.print(file);
}
dnsSpoof.name = split[1];
dnsSpoofing.spoofs.dnsSpoof.add(dnsSpoof);
}
String s = convertToXml(dnsSpoofing, dnsSpoofing.class);
FileWriter writer = new FileWriter("charlesHosts/" + file.getName());
writer.write(s);
writer.close();
}
public static String convertToXml(Object source, Class type) {
String result;
StringWriter sw = new StringWriter();
sw.append("<?xml version='1.0' encoding='UTF-8'?>" + "\n");
sw.append("<?charles serialisation-version='2.0' ?>" + "\n");
try {
JAXBContext context = JAXBContext.newInstance(type);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(source, sw);
result = sw.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
return result;
}
}