package service;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;
public class Demo {
public static void main(String[] args) {
String lineTxt = null;
try {
Demo demo = new Demo();
File file = new File("tanx_niginx205.log");
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
while ((lineTxt = br.readLine()) != null) {
//截取需要的参数!
String result = subString(lineTxt, "ex="," HTTP/");
demo.startGet("http://127.0.0.1:20009/clk",result);
}
br.close();
isr.close();
} else {
System.out.println("文件不存在!");
}
} catch (Exception e) {
System.out.println("文件读取错误!");
}
}
public String startGet(String urls,String param){
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
//GET请求直接在链接后面拼上请求参数
String mPath = urls + "?" + param;
URL url = new URL(mPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
//Get请求不需要DoOutPut
conn.setDoOutput(false);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接服务器
conn.connect();
// 取得输入流,并使用Reader读取
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//关闭输入流
finally{
try{
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result.toString();
}
/**
* 截取指定字段
*/
public static String subString(String str, String strStart,String sto) {
/* 找出指定的2个字符在 该字符串里面的 位置 */
int strStartIndex = str.indexOf(strStart);
int stotIndex = str.indexOf(sto);
/* index为负数 即表示该字符串中没有该字符 */
if (strStartIndex < 0) {
return "字符串 :" + str + "中不存在 " + strStart + ", 无法截取目标字符串";
}
if (stotIndex < 0) {
return "字符串 :" + str + "中不存在 " + strStart + ", 无法截取目标字符串";
}
/* 开始截取 */
String result = str.substring(strStartIndex,stotIndex);
return result;
}
}
http向本地发送get请求
最新推荐文章于 2023-02-24 10:00:36 发布