• HttpClient 和HttpConnection 两种方式POST文件


    /**
    * HttpClientPOST文件
    * @param URL
    * @param content 传params时,此参为""
    * @param params
    * @param fileName
    * @return
    */
    public String postUrl(String URL,String content,Map<String,String> params,String fileName){
    String result = "";
    PostMethod postMethod = new PostMethod(URL);
    RequestEntity requestEntity;
    String CHARSET = "UTF-8";
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    String tmp ;
    try {
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    postMethod.getParams().setContentCharset(CHARSET);
    if (content != null) {
    if(fileName == null){
    requestEntity = new StringRequestEntity(content,"text/html",CHARSET);
    }else{
    Part [] parts = new Part[params.size()+1] ;
    int i=0;
    for (Map.Entry<String, String> entry : params.entrySet()){
    parts[i++]=new StringPart(entry.getKey(), entry.getValue());
    }
    parts[i] = new FilePart("pic", new File(fileName),"multipart/form-data",CHARSET);
    requestEntity = new MultipartRequestEntity(parts,postMethod.getParams());
    }
    postMethod.setRequestEntity(requestEntity);
    }
    httpClient.executeMethod(postMethod);
    if(200==postMethod.getStatusCode()){
    is = postMethod.getResponseBodyAsStream();//返回Header里得不到Content-Length 长度或者长度超过1024*1024 会警告:Going to buffer response body of large or unknown size Using getResponseBodyAsStream instead is recommended
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    while(( tmp = br.readLine())!=null){
    result += tmp;
    }
    }else{
    log.error(postMethod.getStatusLine());
    }
    } catch (Exception e) {
    e.printStackTrace();
    }finally{
    postMethod.releaseConnection();
    try {
    is.close();
    isr.close();
    br.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return result;
    }

    /**
    * HttpConnection提交数据
    * @param str URL
    * @param params 提交参数
    * @param fileName 提交文件名
    * @return
    */
    public String httpConn(String str,Map<String, String> params,String fileName){
    String result = null;
    URL url ;
    HttpURLConnection conn = null ;
    InputStream is = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuilder sb = null;
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    try {
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    System.getProperties().setProperty("http.proxyHost",proxy);
    System.getProperties().setProperty("http.proxyPort",port);
    url = new URL(str);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setUseCaches(false);
    conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
    conn.setRequestProperty("Charsert", CHARSET);
    conn.setRequestProperty("Content-Type",MULTIPART_FROM_DATA+ ";boundary=" + BOUNDARY);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    dos = new DataOutputStream(conn.getOutputStream());
    sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()){
    sb.append(PREFIX);
    sb.append(BOUNDARY);
    sb.append(LINEND);
    sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
    sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
    sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
    sb.append(LINEND);
    sb.append(entry.getValue());
    sb.append(LINEND);
    }
    if(log.isInfoEnabled())
    log.info(sb);
    dos.write(sb.toString().getBytes());
    sb.delete(0, sb.length());
    sb.reverse();
    if(fileName!=null){
    sb.append(PREFIX);
    sb.append(BOUNDARY);
    sb.append(LINEND);
    sb.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + fileName + "\"" + LINEND);
    sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
    sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
    sb.append(LINEND);
    if(log.isInfoEnabled())
    log.info(sb);
    dos.write(sb.toString().getBytes());
    InputStream img = new FileInputStream(fileName);
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = img.read(buffer)) != -1){
    dos.write(buffer, 0, len);
    }
    img.close();
    dos.write(LINEND.getBytes());
    }
    // 请求结束标志
    String end_data = PREFIX + BOUNDARY + PREFIX + LINEND;
    if(log.isInfoEnabled())
    log.info(end_data);
    dos.write(end_data.getBytes());
    dos.flush();
    //dos.close();
    int code = conn.getResponseCode();
    if(code==200){
    is = conn.getInputStream();
    }else{
    log.error(conn.getResponseCode()+conn.getResponseMessage());
    is = conn.getErrorStream();
    }
    dis = new DataInputStream(is);
    byte b[] = new byte[dis.available()];
    dis.read(b);
    result = new String(b);
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    try {
    is.close();
    dis.close();
    conn.disconnect();
    } catch (IOException e) {
    e.printStackTrace();
    }

    }
    return result ;
    }

  • 相关阅读:
    CentOS7搭建SFTP服务
    MySQL主从异常恢复
    MySQL主从复制配置
    Docker安装MySQL8.0
    CentOS7安装JDK1.8
    RabbitMQ死信队列
    RabbitMQ重试机制
    RabbitMQ消息可靠性传输
    TCP/IP的Socket编程
    c#网络编程使用tcpListener和tcpClient
  • 原文地址:https://www.cnblogs.com/langke93/p/2259070.html
Copyright © 2020-2023  润新知