发送http请求

来源:互联网 发布:知乎2018校园招聘 编辑:程序博客网 时间:2024/06/05 01:03
package util;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.HashMap;import java.util.Map;public class HttpURLUtil {    /**     *      * 描述:   发送http请求     * @param @param url     * @param @param method     * @param @param urlParams     * @param @return      * @return String      * @throws     *     */    public static String openUrl(String url, String method,String urlParams) {        String response = null;        InputStream is = null;        if (method.equals("GET")) {            url = url + "?" + urlParams;        }         try {            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒             if (!method.equals("GET")) {                 httpURLConnection.setRequestProperty("content-type", "text/html;charset=utf-8");                 httpURLConnection.setRequestMethod("POST");                 httpURLConnection.setDoOutput(true);                    OutputStream out = httpURLConnection.getOutputStream();                    out.write(urlParams.getBytes("UTF-8"));                    out.flush();                    out.close();                }             int responseCode = httpURLConnection.getResponseCode();                if (responseCode == 200) {                    is = httpURLConnection.getInputStream();                } else {                    is = httpURLConnection.getErrorStream();                }                response = read(is);        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return response;    }    public static String uploadFile(String httpUrl,String fileId, String filename,InputStream inputStream,Map<String,Object> parameters) {         String end = "\r\n";         String twoHyphens = "--";         String boundary = fileId;        try {            String result = "";            URL url = new URL(httpUrl + "?"+ encodeUrl(parameters));            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setDoInput(true);            httpURLConnection.setDoOutput(true);            httpURLConnection.setUseCaches(false);            httpURLConnection.setRequestMethod("POST");            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");            httpURLConnection.setRequestProperty("Charset", "UTF-8");            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());            dos.writeBytes(twoHyphens + boundary + end);            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename+ "\"" + end);            dos.writeBytes(end);            byte[] buffer = new byte[8192]; // 8k            int count = 0;            while ((count = inputStream.read(buffer)) != -1) {                dos.write(buffer, 0, count);            }            inputStream.close();            dos.writeBytes(end);            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);            dos.flush();            if (httpURLConnection.getResponseCode() == 200) {                InputStream is = httpURLConnection.getInputStream();                InputStreamReader isr = new InputStreamReader(is, "utf-8");                BufferedReader br = new BufferedReader(isr);                result = br.readLine();                is.close();            } else {                result = String.valueOf(httpURLConnection.getResponseCode());            }            dos.close();            return result;        } catch (Exception e) {            e.printStackTrace();            return "101";        }    }    /**     * 读流信息     * @param in     * @return     * @throws IOException     */    private static String read(InputStream in) throws IOException {        StringBuilder sb = new StringBuilder();        BufferedReader r = new BufferedReader(new InputStreamReader(in,"utf-8"));        for (String line = r.readLine(); line != null; line = r.readLine()) {            sb.append(line);        }        in.close();        return sb.toString();    }    /**     * 将Key-value转换成用&号链接的URL查询参数形式。     *      * @param parameters     * @return     */    private static String encodeUrl(Map<String,Object> parameters) {        if (parameters == null) {            return "";        }        StringBuilder sb = new StringBuilder();        boolean first = true;        for (String key : parameters.keySet()) {            if (first) {                first = false;            } else {                sb.append("&");            }            sb.append(key + "=" + parameters.get(key).toString());        }        return sb.toString();    }    public static void main(String[] args) throws FileNotFoundException  {      File f=new File("c://45.png");      FileInputStream fi=new FileInputStream(f);      String s=uploadFile("http://www.daohangla.cn/service/tempFileUpLoadServlet.c","2013040915143765151941", "45.png", fi, new HashMap<String, Object>());      System.out.println(s);    }}
0 0