Java Code Examples for java.net.URLConnection#setDoOutput()

The following examples show how to use java.net.URLConnection#setDoOutput() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExceptionLogger.java    From scenic-view with GNU General Public License v3.0 7 votes vote down vote up
private static void doSubmit(final String submission) {
    try {
        // Construct data
        String data = URLEncoder.encode("submission", "UTF-8") + "=" + URLEncoder.encode(submission, "UTF-8");

        // Send data
        URL url = new URL("http://www.jonathangiles.net/scenicView/exceptionLogger.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
        wr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: CheckForUpdateAction.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
private String getContent(String url) {
	try {
		URL u = new URL(url);
		URLConnection uc = u.openConnection();
		uc.setDoOutput(true);

		StringBuffer sbuf = new StringBuffer();
		BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

		try {
			String res = in.readLine();
			while ((res = in.readLine()) != null) {
				sbuf.append(res);
			}
		} finally {
			in.close();
		}

		return sbuf.toString();			
	} catch (IOException ex) {
		return "";
	}
}
 
Example 3
Source File: URLResourceData.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void readMetaData() throws IOException {
  if ( metaDataOK ) {
    if ( ( System.currentTimeMillis() - lastDateMetaDataRead ) < URLResourceData.getFixedCacheDelay() ) {
      return;
    }
    if ( isFixBrokenWebServiceDateHeader() ) {
      return;
    }

  }

  final URLConnection c = url.openConnection();
  c.setDoOutput( false );
  c.setAllowUserInteraction( false );
  if ( c instanceof HttpURLConnection ) {
    final HttpURLConnection httpURLConnection = (HttpURLConnection) c;
    httpURLConnection.setRequestMethod( "HEAD" );
  }
  c.connect();
  readMetaData( c );
  c.getInputStream().close();
}
 
Example 4
Source File: ControlApplet.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
private String callServer(URL serverUrl, Map<String, Object> parms) throws IOException {
    // send the request
    String parameters = this.encodeArgs(parms);
    if (debug != null && debug.equalsIgnoreCase("true")) {
        System.out.println("Sending parameters: " + parameters);
    }
    URLConnection uc = serverUrl.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.println(parameters);
    pw.close();

    // read the response
    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
    String responseStr = in.readLine();
    in.close();
    if (responseStr != null) {
        responseStr = responseStr.trim();
    }
    if (debug != null && debug.equalsIgnoreCase("true")) {
        System.out.println("Receive response: " + responseStr);
    }
    return responseStr;
}
 
Example 5
Source File: UrlClient.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
private static void postToUrl() {
    try {
        URL url = new URL("http://localhost:3333/something");
        URLConnection conn = url.openConnection();
        //conn.setRequestProperty("Method", "POST");
        //conn.setRequestProperty("User-Agent", "Java client");
        conn.setDoOutput(true);
        try (OutputStreamWriter osw =
                     new OutputStreamWriter(conn.getOutputStream())) {
            osw.write("parameter1=value1&parameter2=value2");
            osw.flush();
        }
        try (BufferedReader br =
                     new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 6
Source File: ExploitPlayer.java    From ExploitFixer with GNU General Public License v3.0 6 votes vote down vote up
public String getOnlineUUID() {
	if (onlineUUID == null) {
		try {
			final URLConnection connection = new URL("https://api.mojang.com/users/profiles/minecraft/" + name)
					.openConnection();

			connection.setDoOutput(true);
			connection.connect();

			final BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(connection.getInputStream()));
			final StringBuilder response = new StringBuilder();

			String inputLine;

			while ((inputLine = bufferedReader.readLine()) != null)
				response.append(inputLine).append("\n");

			bufferedReader.close();
			onlineUUID = response.toString();
		} catch (final Exception ignored) {
		}
	}

	return onlineUUID;
}
 
Example 7
Source File: WrapURLConnection.java    From jphp with Apache License 2.0 5 votes vote down vote up
@Signature
public static URLConnection create(String url, @Nullable Proxy proxy) throws IOException {
    URL _url = new URL(url);
    URLConnection urlConnection = proxy == null ? _url.openConnection() : _url.openConnection(proxy);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);

    if (urlConnection instanceof HttpURLConnection) {
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setRequestMethod("GET");
    }

    return urlConnection;
}
 
Example 8
Source File: ForEachJSONPayloadTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private void sendRequest(String addUrl, String query)
        throws IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type",
            "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            output.close();
        }
    }
    InputStream response = connection.getInputStream();
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        response.close();
    }
}
 
Example 9
Source File: BusDatabase.java    From KmbETA-API with GNU General Public License v3.0 5 votes vote down vote up
private JSONArray getBusData(String bn, int dir) throws Exception{
	try {
		URL url = new URL(routedb + "?");
	    URLConnection conn = url.openConnection();
	    conn.setDoOutput(true);

	    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

	    writer.write("bn=" + bn + "&dir=" + dir);
	    writer.flush();
	    
	    String line;
	    String data = "";
	    
	    BufferedReader reader = new BufferedReader(new 
                InputStreamReader(conn.getInputStream()));
	    while ((line = reader.readLine()) != null) {
	        data += line;
	     }
	    
	    if (data == ""){
	    	return null;
	    }
	    
	    data = data.substring(2, data.length());
	    data = data.substring(0, data.length() - 2);
	    data = "[" + data + "]";
	    
	    if (data.equals("[]")){
	    	return null;
	    }
	    
		return new JSONArray(data);
	} catch (Exception e){
		return null;
	}
}
 
Example 10
Source File: ClientHttpRequest.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new multipart POST HTTP request on a freshly opened
 * URLConnection
 *
 * @param connection an already open URL connection
 * @throws IOException
 */
public ClientHttpRequest(URLConnection connection) throws IOException {
    this.connection = connection;
    // july 2019
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);

    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
}
 
Example 11
Source File: DataMapperIntegrationTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected String sendRequest(String addUrl, String request, String contentType) throws IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", contentType + ";charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(request.getBytes(charset));
    } finally {
        if (output != null) {
            output.close();
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }
    return out;
}
 
Example 12
Source File: TGBrowserRequest.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public TGBrowserResponse getResponse() throws Throwable {
	URL url = new URL((TGCommunityWeb.getHomeUrl(this.context) + "/rd.php/sharing/tuxguitar/browser.do"));
	URLConnection conn = url.openConnection();
	conn.setDoOutput(true);
	
	OutputStreamWriter outputStream = new OutputStreamWriter(conn.getOutputStream());
	outputStream.write(this.request);
	outputStream.flush();
	outputStream.close();
	
	return new TGBrowserResponse( conn.getInputStream() ) ;
}
 
Example 13
Source File: DataMapperIntegrationTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected String sendRequest(String addUrl, String request, String contentType) throws IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", contentType + ";charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(request.getBytes(charset));
    } finally {
        if (output != null) {
            output.close();
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }
    return out;
}
 
Example 14
Source File: LateralCacheThread.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/** Description of the Method */
public void writeObj( URLConnection connection, ICacheElement<K, V> cb )
{
    try
    {
        connection.setUseCaches( false );
        connection.setRequestProperty( "CONTENT_TYPE", "application/octet-stream" );
        connection.setDoOutput( true );
        connection.setDoInput( true );
        ObjectOutputStream os = new ObjectOutputStream( connection.getOutputStream() );
        log.debug( "os = " + os );

        // Write the ICacheItem to the ObjectOutputStream
        log.debug( "Writing  ICacheItem." );

        os.writeObject( cb );
        os.flush();

        log.debug( "closing output stream" );

        os.close();
    }
    catch ( IOException e )
    {
        log.error( e );
    }
    // end catch
}
 
Example 15
Source File: JSONClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private JSONObject sendRequest(String addUrl, String query) throws IOException, JSONException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }

    if (!out.isEmpty()) {
        return new JSONObject(out);
    } else {
        return null;
    }
}
 
Example 16
Source File: WatsonTranslateBox.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
private static String doUrl(URL url, String authUser, String authPassword, String data, String ctype, String method) throws IOException {
    StringBuilder sb = new StringBuilder(5000);
    try {
        if(url != null) {
            String userPassword = authUser + ":" + authPassword;
            String encodedUserPassword = Base64.encodeBytes(userPassword.getBytes());
            URLConnection con = (HttpURLConnection) url.openConnection();
            Wandora.initUrlConnection(con);
            con.setRequestProperty ("Authorization", "Basic " + encodedUserPassword);

            con.setDoInput(true);
            con.setUseCaches(false);

            if(method != null && con instanceof HttpURLConnection) {
                ((HttpURLConnection) con).setRequestMethod(method);
                //System.out.println("****** Setting HTTP request method to "+method);
            }

            if(ctype != null) {
                con.setRequestProperty("Content-type", ctype);
            }

            if(data != null && data.length() > 0) {
                con.setRequestProperty("Content-length", data.length() + "");
                con.setDoOutput(true);
                PrintWriter out = new PrintWriter(con.getOutputStream());
                out.print(data);
                out.flush();
                out.close();
            }
            //DataInputStream in = new DataInputStream(con.getInputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));

            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
        }
    }
    catch(IOException ioe) {
        Wandora.getWandora().handleError(ioe);
    }
    catch(Exception e) {
        Wandora.getWandora().handleError(e);
    }
    return sb.toString();
}
 
Example 17
Source File: BackDoor.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
private static URLConnection getConnectionToUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    return conn;
}
 
Example 18
Source File: upload-app-s3.java    From samples with MIT License 4 votes vote down vote up
public static void uploadFileToS3(String filePath, String presignedUrl) {
    try {
        URLConnection urlconnection = null;
        File appFile = new File(filePath);
        URL url = new URL(presignedUrl);

        urlconnection = url.openConnection();
        urlconnection.setUseCaches(false);
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Type", "application/octet-stream");
            ((HttpURLConnection) urlconnection).setRequestProperty("x-amz-tagging", "unsaved=true");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Length", getFileSizeBytes(appFile));
            ((HttpURLConnection) urlconnection).connect();
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        FileInputStream bis = new FileInputStream(appFile);
        System.out.println("Total file size to read (in bytes) : " + bis.available());
        int i;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.close();
        bis.close();

        InputStream inputStream;
        int responseCode = ((HttpURLConnection) urlconnection).getResponseCode();
        if ((responseCode >= 200) && (responseCode <= 202)) {
            inputStream = ((HttpURLConnection) urlconnection).getInputStream();
            int j;
            while ((j = inputStream.read()) > 0) {
                System.out.println(j);
            }

        } else {
            inputStream = ((HttpURLConnection) urlconnection).getErrorStream();
        }
        ((HttpURLConnection) urlconnection).disconnect();
        System.out.println("uploadFileToS3: " + ((HttpURLConnection) urlconnection).getResponseMessage());

    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}
 
Example 19
Source File: PluginUpdater.java    From BedwarsRel with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful.
 */
private boolean read() {
  try {
    final URLConnection conn = this.url.openConnection();
    conn.setConnectTimeout(5000);

    if (this.apiKey != null) {
      conn.addRequestProperty("X-API-Key", this.apiKey);
    }
    conn.addRequestProperty("User-Agent", PluginUpdater.USER_AGENT);
    conn.setDoOutput(true);

    final BufferedReader reader =
        new BufferedReader(new InputStreamReader(conn.getInputStream()));
    final String response = reader.readLine();

    final JSONArray array = (JSONArray) JSONValue.parse(response);

    if (array.isEmpty()) {
      this.plugin.getLogger()
          .warning("The updater could not find any files for the project id " + this.id);
      this.result = UpdateResult.FAIL_BADID;
      return false;
    }

    JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
    this.versionName = (String) latestUpdate.get(PluginUpdater.TITLE_VALUE);
    this.versionLink = (String) latestUpdate.get(PluginUpdater.LINK_VALUE);
    this.versionType = (String) latestUpdate.get(PluginUpdater.TYPE_VALUE);
    this.versionGameVersion = (String) latestUpdate.get(PluginUpdater.VERSION_VALUE);
    this.versionCustom = this.getCustomVersion();

    return true;
  } catch (final IOException e) {
    if (e.getMessage().contains("HTTP response code: 403")) {
      this.plugin.getLogger()
          .severe("dev.bukkit.org rejected the API key provided in plugins/updater/config.yml");
      this.plugin.getLogger()
          .severe("Please double-check your configuration to ensure it is correct.");
      this.result = UpdateResult.FAIL_APIKEY;
    } else {
      this.plugin.getLogger()
          .severe("The updater could not contact dev.bukkit.org for updating.");
      this.plugin.getLogger().severe(
          "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
      this.result = UpdateResult.FAIL_DBO;
    }
    this.plugin.getLogger().log(Level.SEVERE, null, e);
    return false;
  }
}
 
Example 20
Source File: URLConnectionTools.java    From biojava with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Do a POST to a URL and return the response stream for further processing elsewhere.
 * <p>
 * The caller is responsible to close the returned InputStream not to cause
 * resource leaks.
 * @param url the input URL to be read
 * @param data the post data
 * @param timeout
 * @return an {@link InputStream} of response
 * @throws IOException due to an error opening the URL
 */
public static InputStream doPOST(URL url, String data, int timeout) throws IOException
{
	URLConnection conn = openURLConnection(url, timeout);
	conn.setDoOutput(true);
	OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	wr.write(data);
	wr.flush();
	return conn.getInputStream();
}