HttpClient调用别人的借口并写入到文件中

package com.utils;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


import org.apache.commons.lang.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class common {
public static void getFiles(String filepath) throws ParseException {


CloseableHttpClient httpclient = HttpClients.createDefault();// 创建HttpClient对象

try {
String Url = "http://XXXXXXX" ;//你要调用的连接
HttpGet httpget = new HttpGet(Url);

String result = "";
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
String charset = "UTF-8";
// 打印响应状态
if (entity != null) {
charset = getContentCharSet(entity);
// 使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
result = EntityUtils.toString(entity, charset);
String filenameTemp = filepath + lever + pacSname + ".geo.json";// 文件路径+名称+文件类型
File file = new File(filenameTemp);
try {
// 如果文件不存在,则创建新的文件
if (!file.exists()) {
file.createNewFile();
// 创建文件成功后,写入内容到文件里
System.out.println("success create file,the file is " + filenameTemp);
writeFileContent(filenameTemp, result);
} else {
System.out.println(lever + pacSname);
}

} catch (Exception e) {

e.printStackTrace();
}
}


} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static List readTxtFile(String filePath){
ArrayList listPac = new ArrayList<>();
        try {
                String encoding="UTF-8";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                    listPac.add(lineTxt);
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
return listPac;
      
    }

public static String getContentCharSet(final HttpEntity entity) throws ParseException {


if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}


if (StringUtils.isEmpty(charset)) {
charset = "UTF-8";
}
return charset;
}
/**
* 向文件中写入内容

* @param filepath
*            文件路径与名称
* @param newstr
*            写入的内容
* @return
* @throws IOException
*/
public static boolean writeFileContent(String filepath, String newstr) throws IOException {
Boolean bool = false;
String filein = newstr + "\r\n";// 新写入的行,换行
String temp = "";


FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filepath);// 文件路径(包括文件名称)
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();


// 文件原有内容
for (int i = 0; (temp = br.readLine()) != null; i++) {
buffer.append(temp);
// 行与行之间的分隔符 相当于“\n”
buffer = buffer.append(System.getProperty("line.separator"));
}
buffer.append(filein);


fos = new FileOutputStream(file);
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")));// 设置编码
pw.write(buffer.toString().toCharArray());
pw.flush();
bool = true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
// 不要忘记关闭
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return bool;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值