Exemplo n.º 1
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Exemplo n.º 2
0
  private String getResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      URL url = new URL(URL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
Exemplo n.º 3
0
  /**
   * 请求xml数据
   *
   * @param url
   * @param soapAction
   * @param xml
   * @return
   */
  public static String sendXMl(String url, String soapAction, String xml) {
    HttpURLConnection conn = null;
    InputStream in = null;
    InputStreamReader isr = null;
    OutputStream out = null;
    StringBuffer result = null;
    try {
      byte[] sendbyte = xml.getBytes("UTF-8");
      URL u = new URL(url);
      conn = (HttpURLConnection) u.openConnection();
      conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      conn.setRequestProperty("SOAPAction", soapAction);
      conn.setRequestProperty("Content-Length", sendbyte.length + "");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);

      out = conn.getOutputStream();
      out.write(sendbyte);

      if (conn.getResponseCode() == 200) {
        result = new StringBuffer();
        in = conn.getInputStream();
        isr = new InputStreamReader(in, "UTF-8");
        char[] c = new char[1024];
        int a = isr.read(c);
        while (a != -1) {
          result.append(new String(c, 0, a));
          a = isr.read(c);
        }
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      try {
        if (in != null) {
          in.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result == null ? null : result + "";
  }
Exemplo n.º 4
0
  private String postResult(String URL) {
    StringBuffer sb = new StringBuffer();
    try {

      String finalUrl = "";

      String[] parsedUrl = URL.split("\\?");
      String params =
          URLEncoder.encode(parsedUrl[1], "UTF-8").replace("%3D", "=").replace("%26", "&");

      URL url = new URL(parsedUrl[0] + "?" + params);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      conn.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(params);
      wr.flush();
      wr.close();

      boolean redirect = false;
      // normally, 3xx is redirect
      int status = conn.getResponseCode();
      if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true;
      }

      if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
      }
      in.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return sb.toString();
  }
Exemplo n.º 5
0
  void addBody(HttpURLConnection conn, byte[] content) throws IOException {
    conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length));

    // Set default content type if none is set.
    if (conn.getRequestProperty(CONTENT_TYPE) == null) {
      conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
    }
    conn.setDoOutput(true);
    conn.getOutputStream().write(content);
  }
Exemplo n.º 6
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
Exemplo n.º 7
0
 public static boolean hasUpdate(int projectID, String version) {
   try {
     HttpURLConnection con =
         (HttpURLConnection)
             (new URL("https://api.curseforge.com/servermods/files?projectIds=" + projectID))
                 .openConnection();
     con.setRequestMethod("GET");
     con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
     con.setRequestProperty("Pragma", "no-cache");
     con.connect();
     JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
     String[] cdigits =
         ((String) ((JSONObject) json.get(json.size() - 1)).get("name"))
             .toLowerCase()
             .split("\\.");
     String[] vdigits = version.toLowerCase().split("\\.");
     int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
     int a;
     int b;
     for (int i = 0; i < max; i++) {
       a = b = 0;
       try {
         a = Integer.parseInt(cdigits[i]);
       } catch (Throwable t1) {
         char[] c = cdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           a += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       try {
         b = Integer.parseInt(vdigits[i]);
       } catch (Throwable t1) {
         char[] c = vdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           b += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       if (a > b) {
         return true;
       } else if (a < b) {
         return false;
       } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
         return true;
       }
     }
   } catch (Throwable t) {
   }
   return false;
 }
Exemplo n.º 8
0
  public BoardList() {
    URL url = null;
    HttpURLConnection http_url_connection = null;
    int response_code;
    String response_message;
    InputStreamReader in = null;
    BufferedReader reader = null;
    ParserDelegator pd = null;
    try {
      // httpでhtmlファイルを取得する一連の処理
      url = new URL("http://menu.2ch.net/bbsmenu.html");
      http_url_connection = (HttpURLConnection) url.openConnection();
      http_url_connection.setRequestMethod("GET");
      http_url_connection.setInstanceFollowRedirects(false);
      http_url_connection.setRequestProperty("User-Agent", "Monazilla/1.00");
      response_code = http_url_connection.getResponseCode();
      response_message = http_url_connection.getResponseMessage();
      in = new InputStreamReader(http_url_connection.getInputStream(), "SJIS");
      reader = new BufferedReader(in);

      pd = new ParserDelegator();
      pd.parse(reader, cb, true);
      in.close();
      reader.close();
      http_url_connection.disconnect();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
Exemplo n.º 9
0
 // 获得文件长度
 public long getFileSize() {
   int nFileLength = -1;
   try {
     URL url = new URL(siteInfoBean.getSSiteURL());
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     httpConnection.setRequestProperty("User-Agent", "NetFox");
     int responseCode = httpConnection.getResponseCode();
     if (responseCode >= 400) {
       processErrorCode(responseCode);
       return -2; // -2 represent access is error
     }
     String sHeader;
     for (int i = 1; ; i++) {
       // DataInputStream in = new
       // DataInputStream(httpConnection.getInputStream ());
       // Utility.log(in.readLine());
       sHeader = httpConnection.getHeaderFieldKey(i);
       if (sHeader != null) {
         if (sHeader.equals("Content-Length")) {
           nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
           break;
         }
       } else break;
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   Utility.log(nFileLength);
   return nFileLength;
 }
Exemplo n.º 10
0
  private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
    String user;
    String password;
    if (userInfo != null) { // get the user and password
      // System.out.println("UserInfo= " + userInfo );
      int delimiter = userInfo.indexOf(':');
      if (delimiter == -1) {
        user = ParseUtil.decode(userInfo);
        password = null;
      } else {
        user = ParseUtil.decode(userInfo.substring(0, delimiter++));
        password = ParseUtil.decode(userInfo.substring(delimiter));
      }

      String plain = user + ":";
      byte[] nameBytes = plain.getBytes();
      byte[] passwdBytes = password.getBytes();

      // concatenate user name and password bytes and encode them
      byte[] concat = new byte[nameBytes.length + passwdBytes.length];

      System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
      System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length);
      String auth = "Basic " + new String(Base64.encode(concat));
      conn.setRequestProperty("Authorization", auth);
      if (dL > 0) d("Adding auth " + auth);
    }
  }
Exemplo n.º 11
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Exemplo n.º 12
0
 public static String visitWeb(String urlStr) {
   URL url = null;
   HttpURLConnection httpConn = null;
   InputStream in = null;
   try {
     url = new URL(urlStr);
     httpConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection.setFollowRedirects(true);
     httpConn.setRequestMethod("GET");
     httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)");
     in = httpConn.getInputStream();
     return convertStreamToString(in);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       in.close();
       httpConn.disconnect();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return null;
 }
Exemplo n.º 13
0
 public void run() {
   try {
     Thread.sleep(10);
     byte[] buf = getBuf();
     URL url = new URL("http://127.0.0.1:" + port + "/test");
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoOutput(true);
     con.setDoInput(true);
     con.setRequestMethod("POST");
     con.setRequestProperty(
         "Content-Type",
         "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\"");
     OutputStream out = con.getOutputStream();
     out.write(buf);
     out.close();
     InputStream in = con.getInputStream();
     byte[] newBuf = readFully(in);
     in.close();
     if (buf.length != newBuf.length) {
       System.out.println("Doesn't match");
       error = true;
     }
     synchronized (lock) {
       ++received;
       if ((received % 1000) == 0) {
         System.out.println("Received=" + received);
       }
     }
   } catch (Exception e) {
     // e.printStackTrace();
     System.out.print(".");
     error = true;
   }
 }
Exemplo n.º 14
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Exemplo n.º 15
0
  /**
   * 通过post方式访问短信接口
   *
   * @param param sms message, like key1=value1&key2=value2
   * @param isproxy 是否启用代理模式
   * @return
   */
  public String sendPost(String param, boolean isproxy) {
    OutputStreamWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(this.url);
      HttpURLConnection conn = null;

      conn = (HttpURLConnection) realUrl.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestMethod("POST"); // POST方法

      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty(
          "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.connect();

      out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      out.write(param);
      out.flush();
      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("[ERROR]发送 POST 请求出现异常!" + e);
      e.printStackTrace();
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return result;
  }
Exemplo n.º 16
0
  private String putResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      String finalUrl = "";
      if (URL.contains("?")) {
        String[] parsedUrl = URL.split("\\?");
        String params = URLEncoder.encode(parsedUrl[1], "UTF-8");
        finalUrl = parsedUrl[0] + "?" + params;
      } else {
        finalUrl = URL;
      }

      URL url = new URL(finalUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("PUT");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200 | conn.getResponseCode() != 201) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
Exemplo n.º 17
0
  /**
   * 发起查询处理结果请求
   *
   * @param params 请求参数
   * @return 请求结果
   * @throws IOException
   */
  public Result getResult(Map<String, Object> params) throws IOException {
    InputStream is = null;
    HttpURLConnection conn;

    StringBuilder sb = new StringBuilder(HOST + "result");
    sb.append("?");
    for (Map.Entry<String, Object> mapping : params.entrySet()) {
      sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&");
    }
    URL url = new URL(sb.toString().substring(0, sb.length() - 1));

    conn = (HttpURLConnection) url.openConnection();

    // 设置必要参数
    conn.setConnectTimeout(timeout);
    conn.setRequestMethod("GET");
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);

    // 设置时间
    conn.setRequestProperty(DATE, getGMTDate());
    // 设置签名
    conn.setRequestProperty(AUTHORIZATION, sign(params));

    // 创建链接
    conn.connect();

    // 获取返回的信息
    Result result = getResp(conn);

    if (is != null) {
      is.close();
    }
    if (conn != null) {
      conn.disconnect();
    }
    return result;
  }
Exemplo n.º 18
0
  public void run() {
    URL url;
    Base64Encoder base64 = new Base64Encoder();

    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL");
      return;
    }

    try {
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
      httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
    } catch (IOException e) {
      System.err.println("Unable to connect: " + e.getMessage());
      return;
    }

    int prev = 0;
    int cur = 0;

    try {
      while (keepAlive && (cur = httpIn.read()) >= 0) {
        if (prev == 0xFF && cur == 0xD8) {
          jpgOut = new ByteArrayOutputStream(8192);
          jpgOut.write((byte) prev);
        }
        if (jpgOut != null) {
          jpgOut.write((byte) cur);
        }
        if (prev == 0xFF && cur == 0xD9) {
          synchronized (curFrame) {
            curFrame = jpgOut.toByteArray();
          }
          frameAvailable = true;
          jpgOut.close();
        }
        prev = cur;
      }
    } catch (IOException e) {
      System.err.println("I/O Error: " + e.getMessage());
    }
    try {
      jpgOut.close();
      httpIn.close();
    } catch (IOException e) {
      System.err.println("Error closing streams: " + e.getMessage());
    }
    conn.disconnect();
  }
  private byte[] downloadByteArray(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie", cookies);
    if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (null);

    InputStream in = conn.getInputStream();
    byte[] buf = new byte[conn.getContentLength()];
    int read, offset = 0;
    while ((read = in.read(buf, offset, buf.length - offset)) != -1) {
      offset += read;
    }
    return (buf);
  }
Exemplo n.º 20
0
    private String transportHttpMessage(String message) {
      URL serverurl;
      HttpURLConnection connection;

      try {
        serverurl = new URL(this.ServerUrl);
        connection = (HttpURLConnection) serverurl.openConnection();
        connection.setDefaultUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      OutputStreamWriter outstream;
      try {
        outstream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        outstream.write(message);
        outstream.flush();
        /*
        PrintWriter writer = new PrintWriter(outstream);
        writer.write(message);
        writer.flush();
        */
        outstream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      StringBuilder strbuilder = new StringBuilder();
      try {
        InputStreamReader instream = new InputStreamReader(connection.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(instream);

        String str;
        while ((str = reader.readLine()) != null) strbuilder.append(str + "\r\n");

        instream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      connection.disconnect();
      return strbuilder.toString();
    }
Exemplo n.º 21
0
  private String getResponse(String link) {
    try {
      URL urlObject = new URL(link);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setRequestProperty("Cookie", cookieValue);

      return getResponse(httpUrlConnection.getInputStream());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
Exemplo n.º 22
0
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }
Exemplo n.º 23
0
  private int invokeServlet(String url, String method, String user, StringBuffer output)
      throws Exception {
    String httpMethod = "GET";
    if ((method != null) && (method.length() > 0)) httpMethod = method;
    System.out.println("Invoking servlet with HTTP method: " + httpMethod);
    URL u = new URL(url);
    HttpURLConnection c1 = (HttpURLConnection) u.openConnection();
    c1.setRequestMethod(httpMethod);
    if ((user != null) && (user.length() > 0)) {
      // Add BASIC header for authentication
      String auth = user + ":" + password;
      String authEncoded = new sun.misc.BASE64Encoder().encode(auth.getBytes());
      c1.setRequestProperty("Authorization", "Basic " + authEncoded);
    }
    c1.setUseCaches(false);

    // Connect and get the response code and/or output to verify
    c1.connect();
    int code = c1.getResponseCode();
    if (code == HttpURLConnection.HTTP_OK) {
      InputStream is = null;
      BufferedReader input = null;
      String line = null;
      try {
        is = c1.getInputStream();
        input = new BufferedReader(new InputStreamReader(is));
        while ((line = input.readLine()) != null) {
          output.append(line);
          // System.out.println(line);
        }
      } finally {
        try {
          if (is != null) is.close();
        } catch (Exception exc) {
        }
        try {
          if (input != null) input.close();
        } catch (Exception exc) {
        }
      }
    } else if (code == HttpURLConnection.HTTP_MOVED_TEMP) {
      URL redir = new URL(c1.getHeaderField("Location"));
      String line = "Servlet redirected to: " + redir.toString();
      output.append(line);
      System.out.println(line);
    }
    return code;
  }
Exemplo n.º 24
0
  public File download(String songId) {
    try {
      String maxRate = getMaxRate(songId);
      JSONObject songInfo = getSongInfo(songId);
      // 以歌手名字+歌曲名称组成文件名,格式:歌手 - 歌曲名称
      String filename = songInfo.getString("artistName") + " - " + songInfo.getString("songName");

      String link =
          "http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds="
              + songId
              + "&rate="
              + maxRate;

      URL urlObject = new URL(link);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setRequestProperty("Cookie", cookieValue);
      String disposition = httpUrlConnection.getHeaderField("Content-Disposition");
      disposition = disposition.replaceAll("\"", "");
      // 此转码经测试发现有些是UTF-8编码,有些是GBK编码,所以文件名采用另外方式获得
      // disposition = new String(disposition.getBytes("iso-8859-1"),"UTF-8");

      // 根据disposition中信息确定歌曲格式
      String suffix = disposition.substring(disposition.lastIndexOf("."));
      // System.out.println(disposition);

      InputStream inputStream = httpUrlConnection.getInputStream();

      File file = new File(downloadDirectory + "/" + filename + suffix);
      FileOutputStream fos = new FileOutputStream(file);

      byte[] buf = new byte[4096];
      int read = 0;
      while ((read = inputStream.read(buf)) > 0) {
        fos.write(buf, 0, read);
      }
      fos.flush();
      fos.close();
      inputStream.close();
      // System.out.println("完成<"+file.getName()+">歌曲下载!");
      return file;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Exemplo n.º 25
0
 private static InputStream openHttpByteRange(URL url, long offset, long len) throws IOException {
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   String rangeSpec = "bytes=" + offset + "-";
   if (len != -1) {
     long lastByteOffset = offset + len - 1;
     rangeSpec += lastByteOffset;
   }
   conn.setRequestProperty("Range", rangeSpec);
   conn.connect();
   InputStream is = conn.getInputStream();
   if (conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL) {
     System.err.println("HTTP server does not support Range request headers");
     is.close();
     return null;
   }
   return is;
 }
Exemplo n.º 26
0
 Response doSend() throws IOException {
   connection.setRequestMethod(this.verb.name());
   if (connectTimeout != null) {
     connection.setConnectTimeout(connectTimeout.intValue());
   }
   if (readTimeout != null) {
     connection.setReadTimeout(readTimeout.intValue());
   }
   if (boundary != null) {
     connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
   }
   addHeaders(connection);
   if (verb.equals(Verb.PUT) || verb.equals(Verb.POST)) {
     addBody(connection, getByteBodyContents());
   }
   return new Response(connection);
 }
Exemplo n.º 27
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
Exemplo n.º 28
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
Exemplo n.º 29
0
 void addHeaders(HttpURLConnection conn)
 {
   for (String key : headers.keySet())
     conn.setRequestProperty(key, headers.get(key));
 }
 protected void addRequestHeaders(String name, String value) {
   connection.setRequestProperty(name, value);
 }