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
  /**
   * Login with user name and password sent as String parameter to url using POST Interrogation
   *
   * @param username
   * @param userpass
   * @throws IOException
   */
  @And("^I make post message with user: \"([^\"]*)\" and password: \"([^\"]*)\"$")
  public void HttpPostForm(String username, String userpass) throws IOException {

    URL url = new URL("http://dippy.trei.ro");

    HttpURLConnection hConnection = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(true);

    hConnection.setDoOutput(true);
    hConnection.setRequestMethod("POST");

    PrintStream ps = new PrintStream(hConnection.getOutputStream());
    ps.print("user="******"&pass="******";do_login=Login");
    ps.close();

    hConnection.connect();

    if (HttpURLConnection.HTTP_OK == hConnection.getResponseCode()) {
      InputStream is = hConnection.getInputStream();

      System.out.println("!!! encoding: " + hConnection.getContentEncoding());
      System.out.println("!!! message: " + hConnection.getResponseMessage());

      is.close();
      hConnection.disconnect();
    }
  }
Exemplo n.º 4
0
 private HttpURLConnection prepareOutputConnection() throws IOException {
   URL url = new URL(Constants.PROTOCOL, host, port, Constants.CONTEXT_PATH);
   HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
   connection.setRequestMethod(Constants.REQUEST_METHOD_POST);
   connection.setDoOutput(true);
   return connection;
 }
Exemplo n.º 5
0
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
Exemplo n.º 6
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.º 7
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.º 8
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.º 9
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.º 10
0
  /**
   * Method to return a set of hazard data within CACHE_DISTANCE of given location
   *
   * @param location An instance of Location that stores latitude and longitude data
   * @return JSONObject an instance of JSONObject with json encoded hazard data
   * @throws IOException
   * @throws JSONException
   */
  public static JSONObject getHazards(LatLng location) throws IOException, JSONException {
    // request hazards from long / lat data and retrieve json hazards
    // tested and working!

    String longitude = String.valueOf(location.longitude);
    String latitude = String.valueOf(location.latitude);

    String query = String.format("longitude=%s&latitude=%s", longitude, latitude);
    // encode the post query

    // Set a POST connection
    URL url = new URL(site + "/request.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println(query);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();

    BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer hazards = new StringBuffer();
    String inputLine;
    while ((inputLine = response.readLine()) != null) {
      hazards.append(inputLine);
    }

    response.close();

    return new JSONObject(hazards.toString());
  }
Exemplo n.º 11
0
  private void connect() {
    HttpURLConnection con = null;
    String line = "";
    try {
      URL url = new URL(link);
      con = (HttpURLConnection) url.openConnection();
      con.setReadTimeout(readTimeout);
      con.setConnectTimeout(connectionTimeout);
      con.setRequestMethod("GET");
      con.setDoInput(true);

      // Start the connection
      con.connect();

      // Read results from the query
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

      while ((line = reader.readLine()) != null) {
        resultString.add(line);
      }

      reader.close();
    } catch (IOException e) {
      try {
        resultString.add(con.getResponseCode() + "");
      } catch (IOException e1) {
        // TODO: Can't figure response code
      }
    } finally {
      if (con != null) con.disconnect();
    }
  }
Exemplo n.º 12
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.º 13
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.º 14
0
  private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException {

    NameValuePair<Long> run = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c;
    if (host.proxyHost != null)
      c =
          (HttpURLConnection)
              target.openConnection(
                  new Proxy(
                      Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort)));
    else c = (HttpURLConnection) target.openConnection();

    try {
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();

    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();

      // The input is a one liner in the form runId\tAge
      byte[] buffer = new byte[256]; // Very little cost for this new/GC.
      int size = is.read(buffer);

      // We have to close the input stream in order to return it to
      // the cache, so we get it for all content, even if we don't
      // use it. It's (I believe) a bug that the content handlers used
      // by getContent() don't close the input stream, but the JDK team
      // has marked those bugs as "will not fix."
      is.close();

      StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n");
      run = new NameValuePair<Long>();
      run.name = t.nextToken();
      run.value = Long.parseLong(t.nextToken());
    } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) {
      logger.warning("Polling " + target + " got response code " + responseCode);
    }
    return run;
  }
Exemplo n.º 15
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.º 16
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();
    }
  @Override
  protected TicketItemResponse doInBackground(String... urls) {

    TicketItemResponse result = null;

    String uri = GV.URL + "/AddMenuItemToTicketServlet";

    try {

      URL url = new URL(uri);
      CookieManager cookieManager = new CookieManager();
      CookieHandler.setDefault(cookieManager);

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

      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId)));
      params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId)));
      params.add(new BasicNameValuePair("userId", String.valueOf(userId)));
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);

      OutputStream os = connection.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(getQuery(params));
      writer.flush();
      writer.close();
      os.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      StringBuilder temp = new StringBuilder();
      String inputLine;

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

      in.close();

      result = new Gson().fromJson(temp.toString(), TicketItemResponse.class);

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

    return result;
  }
Exemplo n.º 18
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.º 19
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.º 20
0
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
Exemplo n.º 21
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.º 22
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.º 23
0
  public static void main(String args[]) {

    for (int i = 0; i < args.length; i++) {
      try {
        URL u = new URL(args[i]);
        HttpURLConnection http = (HttpURLConnection) u.openConnection();
        http.setRequestMethod("HEAD");
        System.out.println(u + "was last modified at " + new Date(http.getLastModified()));
      } // end try
      catch (MalformedURLException ex) {
        System.err.println(args[i] + " is not a URL I understand");
      } catch (IOException ex) {
        System.err.println(ex);
      }
      System.out.println();
    } // end for
  } // end main
Exemplo n.º 24
0
  private static File download(Config.HostInfo host, NameValuePair<Long> run) throws IOException {

    File jarFile = null;
    FileOutputStream jarOut = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c = null;
    try {
      c = (HttpURLConnection) target.openConnection();
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&runid=" + run.name);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();
    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();
      // We allocate in every method instead of a central buffer
      // to allow concurrent downloads. This can be expanded to use
      // buffer pools to avoid GC, if necessary.
      byte[] buffer = new byte[8192];
      int size;
      while ((size = is.read(buffer)) != -1) {
        if (size > 0 && jarFile == null) {
          jarFile = new File(Config.TMP_DIR, host.name + '.' + run.name + ".jar");
          jarOut = new FileOutputStream(jarFile);
        }
        jarOut.write(buffer, 0, size);
      }
      is.close();
      jarOut.flush();
      jarOut.close();
    } else {
      logger.warning(
          "Downloading run " + run.name + " from " + target + " got response code " + responseCode);
    }
    return jarFile;
  }
Exemplo n.º 25
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.º 26
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.º 27
0
 /**
  * Get the last modification date of a URL.
  *
  * @return last modified timestamp "as is"
  */
 public static long getLastModified(URL url) throws IOException {
   if ("file".equals(url.getProtocol())) {
     // Optimize file: access. Also, this prevents throwing an exception if the file doesn't exist
     // as we try to close the stream below.
     return new File(URLDecoder.decode(url.getFile(), STANDARD_PARAMETER_ENCODING)).lastModified();
   } else {
     // Use URLConnection
     final URLConnection urlConnection = url.openConnection();
     if (urlConnection instanceof HttpURLConnection)
       ((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
     try {
       return getLastModified(urlConnection);
     } finally {
       final InputStream is = urlConnection.getInputStream();
       if (is != null) is.close();
     }
   }
 }
Exemplo n.º 28
0
  public String performPostCall(String requestURL, String param) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

    URL url;
    String response = "";
    try {
      url = new URL(requestURL);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(15000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);

      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(param);

      writer.flush();
      writer.close();
      os.close();
      // int responseCode=conn.getResponseCode();

      // if (responseCode == HttpURLConnection.HTTP_OK) {
      String line;
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      while ((line = br.readLine()) != null) {
        response += line;
      }
      //  }
      //  else {
      //  response= null;

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

    return response;
  }
Exemplo n.º 29
0
 Response doSend(RequestTuner tuner) throws IOException
 {
   connection.setRequestMethod(this.verb.name());
   if (connectTimeout != null) 
   {
     connection.setConnectTimeout(connectTimeout.intValue());
   }
   if (readTimeout != null)
   {
     connection.setReadTimeout(readTimeout.intValue());
   }
   tuner.tune(this);
   addHeaders(connection);
   if (verb.equals(Verb.PUT) || verb.equals(Verb.POST))
   {
     addBody(connection, getByteBodyContents());
   }
   return new Response(connection);
 }
Exemplo n.º 30
0
  private URLConnection prepareConnection(String fileUploadUrl, long fileSize)
      throws RemoteException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FileFaultFaultMsg,
          GuestOperationsFaultFaultMsg, InvalidStateFaultMsg, TaskInProgressFaultMsg,
          MalformedURLException, IOException, ProtocolException {

    // http://stackoverflow.com/questions/3386832/upload-a-file-using-http-put-in-java
    URL url = new URL(fileUploadUrl);
    URLConnection conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    if (conn instanceof HttpURLConnection) {
      ((HttpURLConnection) conn).setRequestMethod("PUT");
    } else {
      throw new IllegalStateException("Unknown connection type");
    }

    conn.setRequestProperty("Content-type", "application/octet-stream");
    conn.setRequestProperty("Content-length", "" + fileSize);
    return conn;
  }