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());
    }
  }
示例#2
0
  /**
   * Send XML Signature to the Server stored in local store in xml file
   *
   * @param filename
   * @throws URLClientException
   */
  public int sendXMLSignatureToServer(String filename) throws URLClientException {
    HttpURLConnection connection = null;
    int respCode;
    try {
      File file = XMLSignatureHelper.getSignatureXMLFile(filename);
      connection = getURLConnectionToServer(signaturesStoreURL);
      connection.setRequestProperty("Cache-Control", "no-cache, no-store");
      connection.setRequestProperty("Pragma", "no-cache");
      connection.setRequestProperty("Content-Type", "text/xml");
      connection.setRequestMethod("POST");
      connection.setDefaultUseCaches(false);
      connection.setInstanceFollowRedirects(false);
      connection.setDoOutput(true);

      OutputStream outputStream = connection.getOutputStream();
      OutputStreamWriter out = new OutputStreamWriter(outputStream);

      BufferedReader in = new BufferedReader(new FileReader(file));
      String str;
      while ((str = in.readLine()) != null) {
        out.write(str);
      }
      out.close();

      respCode = connection.getResponseCode();

      if (respCode != 200) {
        throw new URLClientException("http response code: " + respCode);
      } else {
        System.out.println("Signature was succesfully sent");
        System.out.println("response Code = " + respCode);
      }

      /*
              InputStream is = null;

              try {
                  is = connection.getInputStream();

                  int x;
          	    while ( (x = is.read()) != -1)
          	    {
          		System.out.write(x);
          	    }
          	    is.close();

              } catch (IOException e) {
              }
      */

      //  fis.read(b);

    } catch (IOException e) {
      throw new URLClientException(e);
    } finally {
      connection.disconnect();
    }
    return respCode;
  }
  public static String PostData(String strUrl, String strData) {
    StringBuilder strResult = new StringBuilder("");

    try {
      URL url = new URL(strUrl);
      HttpURLConnection urlConnection = null;

      if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();

        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        urlConnection = https;
      } else {
        urlConnection = (HttpURLConnection) url.openConnection();
      }

      urlConnection.setDefaultUseCaches(false);
      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true);
      urlConnection.setRequestMethod("POST");

      urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");

      OutputStreamWriter outStream =
          new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
      PrintWriter writer = new PrintWriter(outStream);
      writer.write(strData.toString());
      writer.flush();

      if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

        BufferedReader in =
            new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
          strResult.append(inputLine);
        }
      } else {
        strResult.append(urlConnection.getResponseCode());
      }
    } catch (MalformedURLException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      strResult.append(e.toString());
      e.printStackTrace();
    }

    return strResult.toString();
  }
    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();
    }
  /**
   * Issues a request to a service using POST
   *
   * @param service
   * @param request
   * @param contentType
   * @param timeoutConncetion
   * @param timeoutRead
   * @return
   * @throws SocketTimeoutException
   */
  public static String post(
      String service, String request, String contentType, int timeoutConnection, int timeoutRead)
      throws SocketTimeoutException, MalformedURLException {

    try {

      HttpURLConnection urlConnection = (HttpURLConnection) new URL(service).openConnection();

      urlConnection.setDoInput(true);
      urlConnection.setDoOutput(true); // triggers POST
      urlConnection.setUseCaches(false);
      urlConnection.setDefaultUseCaches(false);
      urlConnection.setConnectTimeout(timeoutConnection * 1000);
      urlConnection.setReadTimeout(timeoutRead * 1000);

      urlConnection.setRequestMethod("POST");
      urlConnection.setRequestProperty("Content-Type", contentType);
      urlConnection.setRequestProperty("Accept", "input/xml");

      // write request
      OutputStream out = urlConnection.getOutputStream();
      out.write(request.getBytes());
      out.close();

      // read response
      BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String input;
      while ((input = br.readLine()) != null) {
        sb.append(input + "\n");
      }
      // close buffered reader
      br.close();

      return sb.toString();

    } catch (SocketTimeoutException e) {
      // re-throw the exception
      throw e;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // default
    return null;
  }
  @RequestMapping("url")
  public String checkURL(
      @RequestParam(value = "url", required = false) String u,
      @RequestParam(value = "params", required = false) String params,
      Model model) {
    if (u != null) {
      try {
        final URL url = new URL(u);
        final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(false);
        urlConnection.setDefaultUseCaches(false);
        urlConnection.setInstanceFollowRedirects(true);

        //                urlConnection.setReadTimeout(3000);
        //                urlConnection.setConnectTimeout(3000);

        if (params != null) {
          StringTokenizer st = new StringTokenizer(params, "\n\r");
          while (st.hasMoreTokens()) {
            final String s = st.nextToken();
            final String[] split = s.split(":");
            urlConnection.setRequestProperty(split[0].trim(), split[1].trim());
          }
        }

        try (final InputStream inputStream = urlConnection.getInputStream()) {
          final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
          final StringBuilder sb = new StringBuilder();

          String s = reader.readLine();
          while (s != null) {
            sb.append(s.trim());
            s = reader.readLine();
          }
          model.addAttribute("response", sb.toString());
        } catch (IOException ex) {
          model.addAttribute("response", ex.getMessage());
        }
      } catch (IOException ex) {
        model.addAttribute("response", ex.getMessage());
      }
    }
    model.addAttribute("url", u);
    model.addAttribute("params", params);
    return "/content/maintain/url";
  }
示例#7
0
  /**
   * Send XMLSignature DOM Document to the server...
   *
   * @param doc
   * @throws URLClientException
   */
  public int sendXMLSignatureToServer(Document doc) throws URLClientException {
    int respCode = 0;
    HttpURLConnection connection = null;
    try {
      connection = getURLConnectionToServer(signaturesStoreURL);
      connection.setRequestProperty("Cache-Control", "no-cache, no-store");
      connection.setRequestProperty("Pragma", "no-cache");
      connection.setRequestProperty("Content-Type", "text/xml");
      connection.setRequestMethod("POST");
      connection.setDefaultUseCaches(false);
      connection.setInstanceFollowRedirects(false);
      connection.setDoOutput(true);

      /* get outputs stream from URL Connection*/
      OutputStream outputStream = connection.getOutputStream();
      /* Get ByteArrayOuptutStram with readed xmlSignature DOM */
      ByteArrayOutputStream baos = XMLSignatureHelper.printDOMDocumentToOutputStream(doc);
      /* change OutputStream to InputStream*/
      ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

      /* Write data from InputStream to OutputStream to URL connection*/
      int input = 0;
      while ((input = bais.read()) != -1) {
        outputStream.write(input);
      }
      outputStream.flush();
      outputStream.close();

      respCode = connection.getResponseCode();

      if (respCode != 200) {
        throw new URLClientException("http response code: " + respCode);
      }
      // TODO Udelat nejakou rozumnou reakci na odpoved od Serveru

    } catch (ProtocolException e) {
      throw new URLClientException(e);
    } catch (IOException e) {
      throw new URLClientException(e);
    } finally {
      connection.disconnect();
    }

    return respCode;
  }
示例#8
0
  /**
   * Prepares a connection to the server.
   *
   * @param extraHeaders extra headers to add to the request
   * @return the unopened connection
   * @throws IOException
   */
  private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    connection.setConnectTimeout(connectionTimeoutMillis);
    connection.setReadTimeout(readTimeoutMillis);
    connection.setAllowUserInteraction(false);
    connection.setDefaultUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod("POST");

    setupSsl(connection);
    addHeaders(extraHeaders, connection);

    return connection;
  }
  public static boolean grabLauncher(String md5, File file, int tries) {
    try {
      URL url = new URL("http://s3.amazonaws.com/Minecraft.Download/launcher/launcher.pack.lzma");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

      connection.setUseCaches(false);
      connection.setDefaultUseCaches(false);
      connection.setRequestProperty("Cache-Control", "no-store,max-age=0,no-cache");
      connection.setRequestProperty("Expires", "0");
      connection.setRequestProperty("Pragma", "no-cache");
      if (md5 != null) {
        connection.setRequestProperty("If-None-Match", md5.toLowerCase());
      }
      connection.setConnectTimeout(15000);
      connection.setReadTimeout(10000);

      int code = connection.getResponseCode();
      if (code / 100 == 2) {
        InputStream inputStream = connection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[' '];
        try {
          int read = inputStream.read(buffer);
          while (read >= 1) {
            outputStream.write(buffer, 0, read);
            read = inputStream.read(buffer);
          }
        } finally {
          inputStream.close();
          outputStream.close();
        }
        return true;
      }
      if (tries == 0) {
        return false;
      }
      return grabLauncher(md5, file, tries - 1);
    } catch (Exception e) {
    }
    return false;
  }
 public void setDefaultUseCaches(boolean flag) {
   _flddelegate.setDefaultUseCaches(flag);
 }
示例#11
0
	public static InputStream invokeRequest(String urlToRequest,
			REQUEST_METHOD method, Map<String, String> parameters) {
		if (urlToRequest == null || urlToRequest.trim().length() == 0)
			return null;
		if (parameters == null) {
			parameters = new HashMap<String, String>();
		}
		String urlParameters = constructURLString(parameters);

		if ((method == null || REQUEST_METHOD.GET.equals(method))
				&& urlParameters.length() < 900 && urlParameters.length() > 0) {
			if (urlToRequest.indexOf("?") == -1)
				urlToRequest += "?" + urlParameters;
			else
				urlToRequest += "&" + urlParameters;
			method = REQUEST_METHOD.GET;
		}
		InputStream in = null;
		try {
			URL url = new URL(urlToRequest);
			System.out.println("Reuqest URL:::" + urlToRequest);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			OutputStream out;

			byte[] buff;

			if (REQUEST_METHOD.GET.equals(method)) {
				con.setRequestMethod("GET");
				con.setDoOutput(false);
				con.setDoInput(true);
				con.connect();
				in = con.getInputStream();
			} else if (REQUEST_METHOD.MULTIPART_FORM_DATA.equals(method)) {
				con.setRequestMethod("POST");
				con.setDoOutput(true);
				con.setDoInput(true);
				con.setUseCaches(false);
				con.setDefaultUseCaches(false);

				String boundary = MultipartFormOutputStream.createBoundary();
				// The following request properties were recommended by the MPF
				// class
				con.setRequestProperty("Accept", "*/*");
				con.setRequestProperty("Content-Type",
						MultipartFormOutputStream.getContentType(boundary));
				con.setRequestProperty("Connection", "Keep-Alive");
				con.setRequestProperty("Cache-Control", "no-cache");
				con.connect();
				MultipartFormOutputStream mpout = new MultipartFormOutputStream(
						con.getOutputStream(), boundary);
				// First, write out the parameters
				for (Map.Entry<String, String> entry : parameters.entrySet()) {
					mpout.writeField(entry.getKey(), entry.getValue());
				}
				// Now write the image
				String mimeType = "image/jpg";
				String fullFilePath = parameters.get("file_path");
				if (fullFilePath.endsWith("gif")) {
					mimeType = "image/gif";
				} else if (fullFilePath.endsWith("png")) {
					mimeType = "image/png";
				} else if (fullFilePath.endsWith("tiff")) {
					mimeType = "image/tiff";
				}
				mpout.writeFile("uploadFile", mimeType, new File(fullFilePath));
				mpout.flush();
				mpout.close();
				// All done, get the InputStream
				in = con.getInputStream();
			} else {
				con.setRequestMethod("POST");
				con.setDoOutput(true);
				con.setDoInput(true);
				con.connect();
				out = con.getOutputStream();
				buff = urlParameters.getBytes("UTF8");
				out.write(buff);
				out.flush();
				out.close();
				in = con.getInputStream();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;

	}