Esempio n. 1
0
  @Test
  public void shouldFailWholeTransactionIfOneNodeIsBad() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload =
        "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]},"
            + " \"children\": { \"childNode\" : { \"properties\": {\"jcr:primaryType\": \"invalidType\"}}}}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
    connection.disconnect();

    postUrl =
        new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost?mode:depth=1");
    connection = (HttpURLConnection) postUrl.openConnection();

    // Make sure that we can retrieve the node with a GET
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND));
    connection.disconnect();
  }
Esempio n. 2
0
  @Test
  public void shouldNotPostNodeWithInvalidPrimaryType() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload =
        "{ \"properties\": {\"jcr:primaryType\": \"invalidType\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));
    connection.disconnect();

    postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType");
    connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND));
    connection.disconnect();
  }
Esempio n. 3
0
  @Test
  public void shouldRetrieveDataFromXPathQuery() throws Exception {
    final String NODE_PATH = "/nodeForQuery";
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items" + NODE_PATH);
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\" }}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    payload = "//nodeForQuery";
    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(1));

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is(NODE_PATH));
    assertThat((String) result.get("jcr:primaryType"), is("nt:unstructured"));
  }
Esempio n. 4
0
  private HttpURLConnection getURLConnection() throws IOException {
    URL url;
    HttpURLConnection urlConnection;

    try {
      url = new URL(URLAddress);
      urlConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException();
    }

    /* SETTING THE REQUEST METHOD */

    switch (TaskType) {
      case POST:
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        break;
      case DELETE:
        urlConnection.setRequestMethod("DELETE");
        urlConnection.setDoOutput(true);
        break;
      case GET:
        urlConnection.setRequestMethod("GET");
        break;
    }

    /* SETTING URLCONNECTION PARAMETERS */

    urlConnection.setConnectTimeout(30 * 1000);
    urlConnection.setReadTimeout(30 * 1000);

    return urlConnection;
  }
 public void flush() throws IOException {
   lock.lock();
   try {
     while (!requests.isEmpty()) {
       if (closed) {
         logger.error("logger is closed");
         return;
       }
       if (connection == null) {
         connection = (HttpURLConnection) new URL(url).openConnection();
       }
       try {
         connection.setDoOutput(true);
         connection.setRequestMethod("POST");
       } catch (Exception e) {
         logger.error(e);
         // retry
         connection = (HttpURLConnection) new URL(url).openConnection();
         connection.setDoOutput(true);
         connection.setRequestMethod("POST");
       }
       StringBuilder sb = new StringBuilder();
       int i = maxActionsPerBulkRequest;
       String request;
       while ((request = requests.poll()) != null && (i-- >= 0)) {
         sb.append(request);
       }
       OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
       writer.write(sb.toString());
       writer.close();
       if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
         // read response
         if (logresponses) {
           sb.setLength(0);
           BufferedReader in =
               new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
           String s;
           while ((s = in.readLine()) != null) {
             sb.append(s);
           }
           in.close();
           logger.info(sb.toString());
         }
       } else {
         throw new AppenderLoggingException(
             "no OK response: "
                 + connection.getResponseCode()
                 + " "
                 + connection.getResponseMessage());
       }
     }
   } catch (Throwable t) {
     logger.error(t);
     closed = true;
     throw new AppenderLoggingException("Elasticsearch HTTP error", t);
   } finally {
     lock.unlock();
   }
 }
Esempio n. 6
0
  @Test
  public void shouldPostNodeToValidPathWithMixinTypes() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:mixinTypes\": \"mix:referenceable\"}}";
    connection.getOutputStream().write(payload.getBytes());

    JSONObject body = new JSONObject(getResponseFor(connection));
    assertThat(body.length(), is(1));

    JSONObject properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    JSONArray values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType");
    connection = (HttpURLConnection) postUrl.openConnection();

    // Make sure that we can retrieve the node with a GET
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
    body = new JSONObject(getResponseFor(connection));

    assertThat(body.length(), is(1));

    properties = body.getJSONObject("properties");
    assertThat(properties, is(notNullValue()));
    assertThat(properties.length(), is(3));
    assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured"));
    assertThat(properties.getString("jcr:uuid"), is(notNullValue()));

    values = properties.getJSONArray("jcr:mixinTypes");
    assertThat(values, is(notNullValue()));
    assertThat(values.length(), is(1));
    assertThat(values.getString(0), is("mix:referenceable"));

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK));
    connection.disconnect();
  }
  // 活动短信发送
  public static void noteSend(String str, String mobile) {
    String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
    String account = "cf_CatMiao";
    String password = "******";
    String content = new String("冰川网贷:" + str);
    try {
      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true); // 允许连接提交信息
      connection.setRequestMethod("POST"); // 网页提交方式“GET”、“POST”
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("Connection", "Keep-Alive");
      StringBuffer sb = new StringBuffer();
      sb.append("account=" + account);
      sb.append("&password="******"&mobile=" + mobile);
      sb.append("&content=" + content);
      OutputStream os = connection.getOutputStream();
      os.write(sb.toString().getBytes());
      os.close();

      String line, result = "";
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line + "\n";
      }
      in.close();
      System.out.println("result=" + result);
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
  }
  private void configBody(String params) throws IOException {
    try {
      byte[] postData = params.getBytes(ENCODING_UTF);
      int postDataLength = postData.length;
      connection.setDoOutput(true);
      connection.setRequestProperty("charset", ENCODING_UTF);
      connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
      connection.setUseCaches(false);
      wr = new DataOutputStream(connection.getOutputStream());
      wr.write(postData);
    } catch (IOException e) {
      if (e instanceof ConnectException)
        throw new IOException("Problemas ao tentar conectar com o servidor.");

      throw new IOException("Problemas ao processar dados para envio.");
    } finally {
      if (wr != null) {
        try {
          wr.flush();
          wr.close();
        } catch (IOException e) {
          L.output(e.getMessage());
        }
      }
    }
  }
  public static final HTTPStream createHTTPStream(
      String address,
      boolean isPost,
      byte[] postData,
      String headers,
      int timeOutMs,
      java.lang.StringBuffer responseHeaders) {
    try {
      HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

      if (connection != null) {
        try {
          if (isPost) {
            connection.setConnectTimeout(timeOutMs);
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);

            OutputStream out = connection.getOutputStream();
            out.write(postData);
            out.flush();
          }

          return new HTTPStream(connection);
        } catch (Throwable e) {
          connection.disconnect();
        }
      }
    } catch (Throwable e) {
    }

    return null;
  }
  public HurlStackConnection(
      String method,
      String url,
      boolean followRedirects,
      boolean useCaches,
      int connectTimeout,
      int readTimeout)
      throws IOException {
    Logger.debug(getClass().getSimpleName(), "creating new connection");

    URL urlObj = new URL(url);

    if (urlObj.getProtocol().equals("https")) {
      mConnection = (HttpsURLConnection) urlObj.openConnection();
    } else {
      mConnection = (HttpURLConnection) urlObj.openConnection();
    }

    mConnection.setDoInput(true);
    mConnection.setDoOutput(true);
    mConnection.setConnectTimeout(connectTimeout);
    mConnection.setReadTimeout(readTimeout);
    mConnection.setUseCaches(useCaches);
    mConnection.setInstanceFollowRedirects(followRedirects);
    mConnection.setRequestMethod(method);
  }
Esempio n. 11
0
  /**
   * POST
   *
   * @param url
   * @param content
   * @return
   */
  public static String post(String url, String content) {
    String result = "";
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      connection.setConnectTimeout(connectTimeout);
      connection.setReadTimeout(readTimeout);

      String postData = content;

      OutputStream out = connection.getOutputStream();
      out.write(postData.getBytes(DEFAULT_CHARSET));
      out.flush();

      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
        InputStream is = connection.getInputStream();
        int readCount;
        byte[] buffer = new byte[1024];
        while ((readCount = is.read(buffer)) > 0) {
          bout.write(buffer, 0, readCount);
        }
        is.close();
      }
      connection.disconnect();
      result = bout.toString();
    } catch (IOException e) {
      logger.error("{}", e.getMessage(), e);
    }
    return result;
  }
Esempio n. 12
0
  @Test
  public void uploadFile() throws Exception {
    Path pwd = Paths.get("").toAbsolutePath();
    Path fileUploadPath = Paths.get(pwd.toString(), "/test-upload.txt");
    URL url = new URL("http://" + HOST + ":" + PORT + "/upload" + fileUploadPath);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("PUT");

    connection.setDoOutput(true);
    connection.setDoInput(true);

    String fileContent = "The quick brown fox jumps over the lazy dog.";
    byte[] fileContentBytes = fileContent.getBytes();
    connection.setRequestProperty("Content-Length", "" + Integer.toString(fileContentBytes.length));

    try (OutputStream outputStream = connection.getOutputStream()) {
      outputStream.write(fileContentBytes);
    }

    Assert.assertEquals(connection.getResponseMessage(), 200, connection.getResponseCode());

    assertFileWasUploaded(fileUploadPath, fileContent);

    fileUploadPath.toFile().delete();
  }
Esempio n. 13
0
  private static HttpURLConnection sendPost(String reqUrl, Map<String, String> parameters) {
    HttpURLConnection urlConn = null;
    try {
      StringBuffer params = new StringBuffer();
      if (parameters != null) {
        for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext(); ) {
          String name = iter.next();
          String value = parameters.get(name);
          params.append(name + "=");
          params.append(URLEncoder.encode(value, "UTF-8"));
          if (iter.hasNext()) params.append("&");
        }
      }

      URL url = new URL(reqUrl);
      urlConn = (HttpURLConnection) url.openConnection();
      urlConn.setRequestMethod("POST");
      urlConn.setConnectTimeout(5000); // (单位:毫秒)jdk
      urlConn.setReadTimeout(5000); // (单位:毫秒)jdk 1.5换成这个,读操作超时
      urlConn.setDoOutput(true);
      byte[] b = params.toString().getBytes();
      urlConn.getOutputStream().write(b, 0, b.length);
      urlConn.getOutputStream().flush();
      urlConn.getOutputStream().close();
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return urlConn;
  }
Esempio n. 14
0
  public static void xs3_upload_by_url(URL xs3_url, String file_path) throws IOException {

    BufferedInputStream xs3_instream = null;
    BufferedOutputStream xs3_outstream = null;
    try {
      HttpURLConnection http_conn = (HttpURLConnection) xs3_url.openConnection();
      http_conn.setDoOutput(true);
      http_conn.setRequestMethod("PUT");

      http_conn.setRequestProperty("Content-Type", "image/jpeg");
      http_conn.setRequestProperty("x-amz-acl", "public-read");

      xs3_outstream = new BufferedOutputStream(http_conn.getOutputStream());
      xs3_instream = new BufferedInputStream(new FileInputStream(new File(file_path)));

      byte[] buffer = new byte[1024];
      int xs3_offset = 0;
      while ((xs3_offset = xs3_instream.read(buffer)) != -1) {
        xs3_outstream.write(buffer, 0, xs3_offset);
        xs3_outstream.flush();
      }

      System.out.println("xs3_http_status : " + http_conn.getResponseCode());
      System.out.println("xs3_http_headers: " + http_conn.getHeaderFields());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != xs3_outstream) xs3_outstream.close();
      if (null != xs3_instream) xs3_instream.close();
    }
  }
Esempio n. 15
0
  private String query(String method, HashMap<String, String> args) {
    Mac mac = null;
    SecretKeySpec key = null;
    args.put("method", method);
    long time = System.currentTimeMillis() / 1000L;
    args.put("nonce", "" + (int) (time));
    String postData = "";
    for (Iterator argumentIterator = args.entrySet().iterator(); argumentIterator.hasNext(); ) {
      Map.Entry argument = (Map.Entry) argumentIterator.next();

      if (postData.length() > 0) {
        postData += "&";
      }
      postData += argument.getKey() + "=" + argument.getValue();
    }
    try {
      key = new SecretKeySpec(apisecret.getBytes("UTF-8"), "HmacSHA512");
      mac = Mac.getInstance("HmacSHA512");
      mac.init(key);
      URL queryUrl = new URL("https://btc-e.com/tapi/");
      HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Java Test client)");
      connection.setRequestProperty("Key", apikey);
      connection.setRequestProperty(
          "Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
      connection.getOutputStream().write(postData.getBytes());
      StringWriter writer = new StringWriter();
      IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
      return writer.toString();
    } catch (Exception ex) {
      utils.logger.log(true, ex.getMessage());
    }
    return new String();
  }
  private byte[] downloadUrl(String pFileUrl) throws InterruptedException, JSONException {
    ByteArrayOutputStream vResult = new ByteArrayOutputStream();
    vResult.reset();

    try {
      Log.d("PhoneGapLog", "Downloading " + pFileUrl);

      URL vUrl = new URL(pFileUrl);

      HttpURLConnection vHTTP = (HttpURLConnection) vUrl.openConnection();
      vHTTP.setRequestMethod("GET");
      if (Build.VERSION.SDK_INT
          < 13 /*HONEYCOMB_MR2*/) // To avoid download issue. Should be adjusted.
      vHTTP.setDoOutput(true);
      vHTTP.connect();

      Log.d("PhoneGapLog", "Download start");

      InputStream vStream = vHTTP.getInputStream();

      int vReaded = 0;
      byte[] buffer = new byte[1024];
      while ((vReaded = vStream.read(buffer)) > 0) vResult.write(buffer, 0, vReaded);

      buffer = null;
      Log.d("PhoneGapLog", "Download f inished");
    } catch (FileNotFoundException e) {
      Log.d("PhoneGapLog", "File Not Found: " + e);
    } catch (IOException e) {
      Log.d("PhoneGapLog", "Error: " + e);
    }

    return vResult.toByteArray();
  }
Esempio n. 17
0
  @Override
  public String getCiteItem() {
    String baseurl = "http://pubs.rsc.org/en/content/getformatedresult/";

    String doi = null;
    String posturl = null;
    try {
      Document doc = Jsoup.connect(url).timeout(30000).get();
      doi = doc.select("input#DOI").attr("value");
      posturl = baseurl + doi.toLowerCase() + "?downloadtype=article";
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
      return null;
    } catch (IOException e2) {
      e2.printStackTrace();
      return null;
    }

    HttpURLConnection con = null;
    try {
      String postParams = "ResultAbstractFormat=BibTex&go=";

      URL u = new URL(posturl);
      con = (HttpURLConnection) u.openConnection();
      con.setRequestMethod("POST");
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setUseCaches(false);
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      con.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:37.0) Gecko/20100101 Firefox/37.0");

      @SuppressWarnings("resource")
      OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
      osw.write(postParams);
      osw.flush();
      osw.close();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (con != null) {
        con.disconnect();
      }
    }

    StringBuilder buffer = new StringBuilder();
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
      String temp;
      while ((temp = br.readLine()) != null) {
        buffer.append(temp);
        buffer.append("\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    return buffer.toString();
  }
  private static TwitterAuthenticated getTwitterAuthentication(String base64Encoded)
      throws Exception {
    // Create a HTTP Post to twitter platform
    final HttpURLConnection conn = getHTTPUrlConnection(Constants.Twitter.URL_TOKEN);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.setRequestProperty("Authorization", "Basic " + base64Encoded);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Send post request
    conn.setDoOutput(true);
    final DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes("grant_type=client_credentials");
    wr.flush();
    wr.close();

    final int responseCode = conn.getResponseCode();
    // If success
    if (responseCode == 200) {
      // Read the response, and build the TwitterAuthenticated object
      final TwitterAuthenticated authenticated =
          new Gson()
              .fromJson(
                  new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8")),
                  TwitterAuthenticated.class);
      return authenticated;
    }

    return null;
  }
 private void postToLoggly(final String event) {
   try {
     assert endpointUrl != null;
     URL endpoint = new URL(endpointUrl);
     final HttpURLConnection connection;
     if (proxy == null) {
       connection = (HttpURLConnection) endpoint.openConnection();
     } else {
       connection = (HttpURLConnection) endpoint.openConnection(proxy);
     }
     connection.setRequestMethod("POST");
     connection.setDoOutput(true);
     connection.addRequestProperty("Content-Type", this.layout.getContentType());
     connection.connect();
     sendAndClose(event, connection.getOutputStream());
     connection.disconnect();
     final int responseCode = connection.getResponseCode();
     if (responseCode != 200) {
       final String message = readResponseBody(connection.getInputStream());
       addError("Loggly post failed (HTTP " + responseCode + ").  Response body:\n" + message);
     }
   } catch (final IOException e) {
     addError("IOException while attempting to communicate with Loggly", e);
   }
 }
Esempio n. 20
0
 @Override
 public OutputStream get() {
   String expanded = repositoryURL.toString() + "/repo/sendobject";
   try {
     HttpURLConnection connection = (HttpURLConnection) new URL(expanded).openConnection();
     connection.setDoOutput(true);
     connection.setDoInput(true);
     connection.setUseCaches(false);
     connection.setRequestMethod("POST");
     connection.setChunkedStreamingMode(4096);
     connection.setRequestProperty("content-length", "-1");
     connection.setRequestProperty("content-encoding", "gzip");
     OutputStream out = connection.getOutputStream();
     final ReportingOutputStream rout =
         HttpUtils.newReportingOutputStream(connection, out, true);
     return new FilterOutputStream(rout) {
       @Override
       public void close() throws IOException {
         super.close();
         compressedSize += ((ReportingOutputStream) super.out).compressedSize();
         uncompressedSize += ((ReportingOutputStream) super.out).unCompressedSize();
       }
     };
   } catch (Exception e) {
     throw Throwables.propagate(e);
   }
 }
Esempio n. 21
0
 private static String fetchTask() throws IOException, InterruptedException {
   String[] paramsNames = {"os.name", "os.arch", "os.version", "java.vendor", "java.version"};
   StringBuffer params = new StringBuffer();
   int max = paramsNames.length;
   for (String p : paramsNames) {
     params.append(p.replace('.', '_'));
     params.append('=');
     params.append(URLEncoder.encode(System.getProperty(p), "utf-8"));
     if (--max > 0) params.append('&');
   }
   String urlParameters = params.toString();
   //		System.out.println(urlParameters);
   String request = FETCH_REQUEST_URL + FETCH_REQUEST_URL_EXT;
   URL url = new URL(request);
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   connection.setDoOutput(true);
   connection.setDoInput(true);
   connection.setInstanceFollowRedirects(false);
   connection.setRequestMethod("POST");
   connection.setRequestProperty("charset", "utf-8");
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   connection.setRequestProperty(
       "Content-Length", Integer.toString(urlParameters.getBytes().length));
   connection.setUseCaches(false);
   connection.getOutputStream().write(urlParameters.getBytes());
   connection.getOutputStream().close();
   StreamWrapper requestStream =
       StreamWrapper.createStreamWrapper(connection.getInputStream(), false);
   requestStream.join();
   String response = requestStream.toString();
   return response;
 }
Esempio n. 22
0
  // A general method for calling api and receiving response
  private String callAPI(final JSONObject param, final String api) {
    URL apiURL;
    try {

      apiURL = new URL(url + api);
      HttpURLConnection conn;

      conn = (HttpURLConnection) apiURL.openConnection();

      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
      wr.write(param.toString());
      wr.flush();

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

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
      in.close();
      //			System.out.println(response.toString());
      return response.toString();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
 // 获取版本更新信息
 private Boolean GetVersion(String strUrl, int mar, int min) {
   Boolean rv = false;
   try {
     URL url = new URL(strUrl);
     String para = new String("CUserName=tk&&CMend=getversion");
     // 打开http连接
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     // 设置请求方式
     httpConnection.setRequestMethod("POST");
     // post这俩个需要改为true
     httpConnection.setRequestProperty("contentType", "GBK");
     httpConnection.setRequestProperty("Content-Length", String.valueOf(para.getBytes().length));
     httpConnection.setDoOutput(true);
     httpConnection.setDoInput(true);
     httpConnection.setUseCaches(false);
     // 向服务器写数据
     httpConnection.getOutputStream().write(para.getBytes());
     // 获取服务器回复
     int nResponse = httpConnection.getResponseCode();
     if (nResponse == 200) {
       InputStream is = httpConnection.getInputStream();
       String result = util.readMyInputStream(is);
       Log.i("TKTEST", result);
     } else {
       // Toast.makeText(this, "请求失败错误码"+nResponse, Toast.LENGTH_SHORT).show();
     }
   } catch (Exception e) {
     e.printStackTrace();
     // Toast.makeText(this, "发生异常,请求失败", Toast.LENGTH_SHORT).show();
   }
   rv = true;
   return rv;
 }
Esempio n. 24
0
  private String openPostUrl(String url, HashMap<String, String> params, String secret, String data)
      throws MalformedURLException, IOException, NoSuchAlgorithmException {

    params.put("method", "POST");

    String charset = "UTF-8";

    String data_hashed = data; // encodeUrl(data,secret);

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", charset);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
    OutputStream output = null;

    try {
      output = conn.getOutputStream();
      output.write(data_hashed.getBytes(charset));

    } finally {
      if (output != null)
        try {
          output.close();
        } catch (IOException logOrIgnore) {
        }
    }

    System.out.println(data_hashed.getBytes(charset));
    String response = read(conn.getInputStream());
    conn.disconnect();
    return response;
  }
    protected JSONObject doInBackground(String... params) {
      try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        JSONObject parameters = new JSONObject();
        parameters.put("hash", "274ffe280ad2956ea85f35986958095d");
        parameters.put("seed", "10");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(parameters.toString());
        wr.flush();
        wr.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          result.append(line);
        }

        JSONObject obj = new JSONObject(result.toString());
        return obj;
      } catch (Exception e) {
        this.exception = e;
        return null;
      }
    }
Esempio n. 26
0
 public String getWeatherData(String location) {
   HttpURLConnection con = null;
   InputStream is = null;
   try {
     con = (HttpURLConnection) (new URL(BASE_URL + location)).openConnection();
     con.setRequestMethod("GET");
     con.setDoInput(true);
     con.setDoOutput(true);
     con.connect();
     // Let's read the response
     StringBuffer buffer = new StringBuffer();
     is = con.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(is));
     String line = null;
     while ((line = br.readLine()) != null) buffer.append(line + "\r\n");
     is.close();
     con.disconnect();
     return buffer.toString();
   } catch (Throwable t) {
     t.printStackTrace();
   } finally {
     try {
       is.close();
     } catch (Throwable t) {
     }
     try {
       con.disconnect();
     } catch (Throwable t) {
     }
   }
   return null;
 }
  public void download(String address) {
    StringBuilder jsonHtml = new StringBuilder();
    try {
      // ���� url ����
      URL url = new URL(address);
      // ���ؼ� ��ü ��
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDefaultUseCaches(false);
      conn.setDoInput(true); // �������� �б� ��� ����
      conn.setDoOutput(false); // ������ ���� ��� ����
      conn.setRequestMethod("POST"); // ��� ����� POST

      // ����Ǿ��
      if (conn != null) {
        conn.setConnectTimeout(10000);
        conn.setUseCaches(false);
        // ����Ȯ�� �ڵ尡 ���ϵǾ��� ��
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
          for (; ; ) {
            String line = br.readLine();
            if (line == null) break;
            jsonHtml.append(line);
          }
          br.close();
        }
        conn.disconnect();
      }
    } catch (Exception e) {
      Log.w(TAG, e.getMessage());
    }
  }
Esempio n. 28
0
 public byte[] getImage(String code) {
   HttpURLConnection con = null;
   InputStream is = null;
   try {
     con = (HttpURLConnection) (new URL(IMG_URL + code)).openConnection();
     con.setRequestMethod("GET");
     con.setDoInput(true);
     con.setDoOutput(true);
     con.connect();
     // Let's read the response
     is = con.getInputStream();
     byte[] buffer = new byte[1024];
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     while (is.read(buffer) != -1) baos.write(buffer);
     return baos.toByteArray();
   } catch (Throwable t) {
     t.printStackTrace();
   } finally {
     try {
       is.close();
     } catch (Throwable t) {
     }
     try {
       con.disconnect();
     } catch (Throwable t) {
     }
   }
   return null;
 }
Esempio n. 29
0
 public static void hasUpdate(Player player) {
   try {
     HttpURLConnection c =
         (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection();
     c.setDoOutput(true);
     c.setRequestMethod("POST");
     c.getOutputStream()
         .write(
             ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=17599")
                 .getBytes("UTF-8"));
     String oldVersion = plugin.getDescription().getVersion();
     String newVersion =
         new BufferedReader(new InputStreamReader(c.getInputStream()))
             .readLine()
             .replaceAll("[a-zA-Z ]", "");
     if (!newVersion.equals(oldVersion)) {
       player.sendMessage(
           getPrefix()
               + color(
                   "&cYour server is running &7v"
                       + oldVersion
                       + "&c and the newest is &7v"
                       + newVersion
                       + "&c."));
     }
   } catch (Exception e) {
     return;
   }
 }
Esempio n. 30
0
    /**
     * Do a http operation
     *
     * @param urlConnection the HttpURLConnection to be used
     * @param inputData if not null,will be written to the urlconnection.
     * @param hasOutput if true, read content back from the urlconnection
     * @return Response
     */
    private Response doOperation(
        HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) {
      Response response = null;
      InputStream inputStream = null;
      OutputStream outputStream = null;
      byte[] payload = null;
      try {
        if (inputData != null) {
          urlConnection.setDoOutput(true);
          outputStream = urlConnection.getOutputStream();
          outputStream.write(inputData);
        }
        if (hasOutput) {
          inputStream = urlConnection.getInputStream();
          payload = Util.readFileContents(urlConnection.getInputStream());
        }
        response =
            new Response(urlConnection.getHeaderFields(), urlConnection.getResponseCode(), payload);

      } catch (IOException e) {
        log.error("Error calling service", e);
      } finally {
        Util.close(inputStream);
        Util.close(outputStream);
      }
      return response;
    }