首页 > 代码库 > HttpTool.java

HttpTool.java

HttpTool.java

该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用.

package kingtool;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.Date;/** * http post发送工具 * @author King * */public class HttpTool {    public static void main(String[] args) throws Exception {        String requestUrl = "http://10.15.22.120:9999/httpserver";        String requestData = readStringFromFile("C:\\Users\\King\\Desktop\\connectANSI.xml","GBK");//有乱码,请修改指定编码        //_________________________________________________________________________________________        String returnData=http://www.mamicode.com/HttpTool.sendRequestData("telesales",requestData, requestUrl,"GBK","GBK", 3000,3000);//大家最终只要使用这一句代码就可调用        //_________________________________________________________________________________________    }        /**     * 发送报文     *      * @param appName 应用系统英文名     * @param requestData 请求报文     * @param urlStr    请求地址     * @param connectionTimeout 链接超时时间  1000代表 1秒     * @param readTimeout 读取超时时间 1000代表1秒     * @return     * @throws IOException     * @author King     */    public static String sendRequestData(String appName,String requestData, String urlStr,String sendEncoding,String recvEncoding, int connectionTimeout,int readTimeout) throws IOException{        URL url = null;        HttpURLConnection conn = null;        ByteArrayOutputStream byteOut = null;        BufferedReader readInfo = null;        StringBuffer strBuilder=new StringBuffer();        OutputStream out = null;        try {            System.out.println("请求时间:【"+new Date()+"");            System.out.println("请求地址:【"+urlStr+"");            System.out.println("请求报文:【"+requestData+"");            url = new URL(urlStr);            conn = (HttpURLConnection) url.openConnection();            conn.setRequestMethod("POST");            conn.setRequestProperty("SOAPAction", "\"\"");            conn.setRequestProperty("Accept", "application/soap+xml, application/dime, multipart/related, text/*");            //如果没有下面这一行代码,服务器端可以通过request.getParameter()和request.getInputStream()都接收到相同信息            //conn.setRequestProperty("content-type", "text/xml;charset=GBK");            //如果    有上面这一行代码,服务器端仅能通过request.getInputStream()接收信息            conn.setRequestProperty("User-Agent", "Axis/1.4");            conn.setRequestProperty("Cache-Control", "no-cache");            conn.setRequestProperty("appName", appName);//各系统需要设置应用系统名 appName,如电销为telesales            conn.setUseCaches(false); //忽略缓存            conn.setDoOutput(true); //使用 URL 连接进行输出            conn.setDoInput(true); //使用 URL 连接进行输入            conn.setConnectTimeout(connectionTimeout);//链接超时            conn.setReadTimeout(readTimeout);//读取超时            conn.connect();//建立链接            byteOut = new ByteArrayOutputStream();            byteOut.write(requestData.getBytes(sendEncoding));//以指定编码发送,如果有乱码,修改之            byte[] buf = byteOut.toByteArray();            out = conn.getOutputStream();            out.write(buf);            out.flush();            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {//正确返回                 readInfo = new BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),recvEncoding));//以指定编码读取返回信息,如果有乱码,修改之                String line = null;                while ((line = readInfo.readLine()) != null) {                    strBuilder.append(line);                }            } else {//没有正确返回                readInfo = new BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),recvEncoding));//以指定编码读取返回信息,如果有乱码,修改之                System.out.println("出现异常,返回报文:【"+readInfo+"");                throw new IOException("url请求出现问题,返回编码:" + conn.getResponseCode());            }            System.out.println("返回时间:【"+new Date()+"");            System.out.println("返回报文:【"+strBuilder.toString()+"");        } catch (UnsupportedEncodingException e) {            throw e;        } catch (MalformedURLException e) {            throw e;        } catch (IOException e) {            throw e;        }finally {            try{                if (readInfo != null) {                    readInfo.close();                }                if (byteOut != null) {                    byteOut.close();                }                if (out != null) {                    out.close();                }                if (conn != null) {                    conn.disconnect();                }            }catch(Exception e){                System.out.println("关闭链接出错!"+e.getMessage());            }                    }        return strBuilder.toString();    }                /**     *      * @param filePath 文件绝对路径     * @param encoding 读取文件的编码     * @return     * @author King     * @throws Exception     */    public static String readStringFromFile(String filePath,String encoding) {        File file = new File(filePath);        System.out.println("文件 "+filePath+"存在与否?: "+ file.exists()+"\n");        String tempLine = null;        String retStr = "";        InputStreamReader isr = null;//way1://        FileReader fr = null;//way2        StringBuilder sb = new StringBuilder();        try {            if(file.exists()){                isr = new InputStreamReader(new FileInputStream(file),encoding);//way1://                fr = new FileReader(file);//way2                BufferedReader br = new BufferedReader(isr);//way1://                BufferedReader br =  new BufferedReader(fr);;//way2:                tempLine = br.readLine();                while( tempLine != null ){                    sb.append(tempLine);                    tempLine = br.readLine();                }                retStr = sb.toString();            }        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{                try{                    if(isr!=null)                        isr.close();                }catch(Exception e){                    e.printStackTrace();                }            }         System.out.println("读到的文件内容如下:");        System.out.println(retStr+"\n");        return retStr;    }}

 

HttpTool.java