Java Code Examples for java.net.HttpURLConnection.setInstanceFollowRedirects()

The following are Jave code examples for showing how to use setInstanceFollowRedirects() of the java.net.HttpURLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   Source Code and License Vote up 7 votes
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
// Cronet does not support reading response body of a 302 response.
public void testDisableRedirectsTryReadBody() throws Exception {
    URL url = new URL(NativeTestServer.getFileURL("/redirect.html"));
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    try {
        connection.getInputStream();
        fail();
    } catch (IOException e) {
        // Expected.
    }
    assertNull(connection.getErrorStream());
    connection.disconnect();
}
 
Example 2
Project: GitHub   File: OkUrlFactoryTest.java   Source Code and License Vote up 6 votes
@Test
public void setInstanceFollowRedirectsFalse() throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(302)
      .addHeader("Location: /b")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpURLConnection connection = factory.open(server.url("/a").url());
  connection.setInstanceFollowRedirects(false);
  assertResponseBody(connection, "A");
  assertResponseCode(connection, 302);
}
 
Example 3
Project: ZXingAndroidExt   File: HttpHelper.java   Source Code and License Vote up 6 votes
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
    int redirects = 0;
    while (redirects < 5) {
        URL url = new URL(uri);
        HttpURLConnection connection = safelyOpenConnection(url);
        connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
        connection.setRequestProperty("Accept", contentTypes);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        connection.setRequestProperty("User-Agent", "ZXing (Android)");
        try {
            int responseCode = safelyConnect(connection);
            switch (responseCode) {
                case HttpURLConnection.HTTP_OK:
                    return consume(connection, maxChars);
                case HttpURLConnection.HTTP_MOVED_TEMP:
                    String location = connection.getHeaderField("Location");
                    if (location != null) {
                        uri = location;
                        redirects++;
                        continue;
                    }
                    throw new IOException("No Location");
                default:
                    throw new IOException("Bad HTTP response: " + responseCode);
            }
        } finally {
            connection.disconnect();
        }
    }
    throw new IOException("Too many redirects");
}
 
Example 4
Project: GroupingMessages   File: SettingsFragment.java   Source Code and License Vote up 6 votes
private void asyncCheckLatestAppVersion() {
    try {
        URL url = new URL(getString(R.string.latest_release_url));
        HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
        ucon.setInstanceFollowRedirects(false);
        URL secondURL = new URL(ucon.getHeaderField("Location"));
        String secondUrl = String.valueOf(secondURL);
        String latestVersion = Uri.parse(secondUrl).getLastPathSegment();
        Log.d("GM/updateUrl", secondUrl);
        if (getActivity() != null) {
            String checkUrl = getString(R.string.current_release_url_prefix) + BuildConfig.VERSION_NAME;
            if (secondUrl.equals(checkUrl)) {
                versionSummary = BuildConfig.VERSION_NAME + " " +
                        getString(R.string.version_summary_latest);
            } else {
                versionSummary = BuildConfig.VERSION_NAME + " " +
                        "(" + getString(R.string.version_summary_changed_latest) + latestVersion + ")";
                latestVersionUrl = secondUrl;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    versionPref.setSummary(versionSummary);
                    Log.d("GM/versionChecked", versionSummary);
                }
            });
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: weex-3d-map   File: HttpHelper.java   Source Code and License Vote up 6 votes
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
  int redirects = 0;
  while (redirects < 5) {
    URL url = new URL(uri);
    HttpURLConnection connection = safelyOpenConnection(url);
    connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
    connection.setRequestProperty("Accept", contentTypes);
    connection.setRequestProperty("Accept-Charset", "utf-8,*");
    connection.setRequestProperty("User-Agent", "ZXing (Android)");
    try {
      int responseCode = safelyConnect(connection);
      switch (responseCode) {
        case HttpURLConnection.HTTP_OK:
          return consume(connection, maxChars);
        case HttpURLConnection.HTTP_MOVED_TEMP:
          String location = connection.getHeaderField("Location");
          if (location != null) {
            uri = location;
            redirects++;
            continue;
          }
          throw new IOException("No Location");
        default:
          throw new IOException("Bad HTTP response: " + responseCode);
      }
    } finally {
      connection.disconnect();
    }
  }
  throw new IOException("Too many redirects");
}
 
Example 6
Project: avaire   File: ExpandUrlCommand.java   Source Code and License Vote up 6 votes
private List<String> fetchRedirect(String url, List<String> redirects) throws IOException {
    redirects.add(url);

    HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setInstanceFollowRedirects(false);
    con.connect();

    if (con.getHeaderField("Location") == null) {
        return redirects;
    }
    return fetchRedirect(con.getHeaderField("Location"), redirects);
}
 
Example 7
Project: airgram   File: DefaultHttpDataSource.java   Source Code and License Vote up 6 votes
/**
 * Configures a connection and opens it.
 *
 * @param url The url to connect to.
 * @param postBody The body data for a POST request.
 * @param position The byte offset of the requested data.
 * @param length The length of the requested data, or {@link C#LENGTH_UNBOUNDED}.
 * @param allowGzip Whether to allow the use of gzip.
 * @param followRedirects Whether to follow redirects.
 */
private HttpURLConnection makeConnection(URL url, byte[] postBody, long position,
    long length, boolean allowGzip, boolean followRedirects) throws IOException {
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setConnectTimeout(connectTimeoutMillis);
  connection.setReadTimeout(readTimeoutMillis);
  synchronized (requestProperties) {
    for (Map.Entry<String, String> property : requestProperties.entrySet()) {
      connection.setRequestProperty(property.getKey(), property.getValue());
    }
  }
  if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) {
    String rangeRequest = "bytes=" + position + "-";
    if (length != C.LENGTH_UNBOUNDED) {
      rangeRequest += (position + length - 1);
    }
    connection.setRequestProperty("Range", rangeRequest);
  }
  connection.setRequestProperty("User-Agent", userAgent);
  if (!allowGzip) {
    connection.setRequestProperty("Accept-Encoding", "identity");
  }
  connection.setInstanceFollowRedirects(followRedirects);
  connection.setDoOutput(postBody != null);
  if (postBody != null) {
    connection.setFixedLengthStreamingMode(postBody.length);
    connection.connect();
    OutputStream os = connection.getOutputStream();
    os.write(postBody);
    os.close();
  } else {
    connection.connect();
  }
  return connection;
}
 
Example 8
Project: Codeforces   File: HurlStack.java   Source Code and License Vote up 6 votes
/**
 * Create an {@link HttpURLConnection} for the specified {@code url}.
 */
protected HttpURLConnection createConnection(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Workaround for the M release HttpURLConnection not observing the
    // HttpURLConnection.setFollowRedirects() property.
    // https://code.google.com/p/android/issues/detail?id=194495
    connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());

    return connection;
}
 
Example 9
Project: JuniperBotJ   File: DiscordHttpRequestFactory.java   Source Code and License Vote up 6 votes
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
        throws IOException {
    super.prepareConnection(connection, httpMethod);
    connection.setInstanceFollowRedirects(false);
    connection.setUseCaches(false);
}
 
Example 10
Project: aws-sdk-java-v2   File: ConnectionUtils.java   Source Code and License Vote up 6 votes
public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY);
    connection.setConnectTimeout(1000 * 2);
    connection.setReadTimeout(1000 * 5);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    headers.forEach(connection::addRequestProperty);
    connection.setInstanceFollowRedirects(false);
    connection.connect();

    return connection;
}
 
Example 11
Project: Sega   File: ImageLoader.java   Source Code and License Vote up 6 votes
private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if (b != null) {
        return b;
    }

    //from web
    try {
        Bitmap bitmap;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError) {
            memoryCache.clear();
        }
        return null;
    }
}
 
Example 12
Project: VkAccess   File: VkAccess.java   Source Code and License Vote up 6 votes
private static HttpURLConnection fastConfigureConnection(HttpURLConnection http) {
	http.addRequestProperty("User-Agent",
			"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 VkAuthLib/0.0.1 VkAccess/0.0.1");
	http.addRequestProperty("Accept-Language", "ru-ru,ru;q=0.5");
	http.setInstanceFollowRedirects(true);
	http.setDoInput(true);
	http.setDoOutput(true);
	return http;
}
 
Example 13
Project: PlusGram   File: DefaultHttpDataSource.java   Source Code and License Vote up 6 votes
/**
 * Configures a connection and opens it.
 *
 * @param url The url to connect to.
 * @param postBody The body data for a POST request.
 * @param position The byte offset of the requested data.
 * @param length The length of the requested data, or {@link C#LENGTH_UNBOUNDED}.
 * @param allowGzip Whether to allow the use of gzip.
 * @param followRedirects Whether to follow redirects.
 */
private HttpURLConnection makeConnection(URL url, byte[] postBody, long position,
    long length, boolean allowGzip, boolean followRedirects) throws IOException {
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setConnectTimeout(connectTimeoutMillis);
  connection.setReadTimeout(readTimeoutMillis);
  synchronized (requestProperties) {
    for (Map.Entry<String, String> property : requestProperties.entrySet()) {
      connection.setRequestProperty(property.getKey(), property.getValue());
    }
  }
  if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) {
    String rangeRequest = "bytes=" + position + "-";
    if (length != C.LENGTH_UNBOUNDED) {
      rangeRequest += (position + length - 1);
    }
    connection.setRequestProperty("Range", rangeRequest);
  }
  connection.setRequestProperty("User-Agent", userAgent);
  if (!allowGzip) {
    connection.setRequestProperty("Accept-Encoding", "identity");
  }
  connection.setInstanceFollowRedirects(followRedirects);
  connection.setDoOutput(postBody != null);
  if (postBody != null) {
    connection.setFixedLengthStreamingMode(postBody.length);
    connection.connect();
    OutputStream os = connection.getOutputStream();
    os.write(postBody);
    os.close();
  } else {
    connection.connect();
  }
  return connection;
}
 
Example 14
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   Source Code and License Vote up 5 votes
/**
 * <b>CREATE</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE
 * [&overwrite=<true|false>][&blocksize=<LONG>][&replication=<SHORT>]
 * [&permission=<OCTAL>][&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String create(String path, InputStream is)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL
            .openConnection(
                    new URL(new URL(httpfsUrl), MessageFormat.format(
                            "/webhdfs/v1/{0}?op=CREATE",
                            URLUtil.encodePath(path))), token);
    conn.setRequestMethod("PUT");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    System.out.println("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("PUT");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, false);
        conn.disconnect();
    }

    return resp;
}
 
Example 15
Project: Equella   File: UtilsScriptWrapper.java   Source Code and License Vote up 5 votes
@Override
public ResponseScriptType getResponse(boolean isGET)
{
	try
	{
		final String data = getFormData();

		String extra = "";
		if( isGET && !Check.isEmpty(data) )
		{
			String qs = url.getQuery();
			if( Check.isEmpty(qs) )
			{
				extra += "?" + data;
			}
			else
			{
				extra += "?" + qs + "&" + data;
			}
		}
		final String urlString = url.toString() + extra;

		final URL finalUrl = new URL(urlString);
		final HttpURLConnection conn = (HttpURLConnection) finalUrl.openConnection();

		conn.setRequestMethod(isGET ? "GET" : "POST");
		conn.setAllowUserInteraction(false);
		conn.setInstanceFollowRedirects(true);

		conn.setDoOutput(true);
		conn.setDoInput(true);

		// Send data
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Accept", "*/*");

		if( !isGET )
		{
			try( Writer wr = new OutputStreamWriter(conn.getOutputStream()) )
			{
				if( !isGET )
				{
					wr.write(data);
				}
				wr.flush();
			}
		}

		// Get the response
		final String contentType = conn.getContentType();

		try( InputStream is = conn.getInputStream() )
		{
			if( contentType == null || contentType.startsWith("text/") )
			{
				Reader rd = new InputStreamReader(is);
				StringWriter sw = new StringWriter();
				CharStreams.copy(rd, sw);
				return new ResponseScriptTypeImpl(sw.toString(), conn.getResponseCode(), contentType);
			}
			else
			{
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				ByteStreams.copy(is, os);
				return new ResponseScriptTypeImpl(os.toByteArray(), conn.getResponseCode(), contentType);
			}
		}
	}
	catch( IOException e )
	{
		return new ResponseScriptTypeImpl("ERROR: " + e.getMessage(), 400, "text/plain");
	}
}
 
Example 16
Project: Transwarp-Sample-Code   File: PseudoWebHDFSConnection.java   Source Code and License Vote up 5 votes
/**
 * curl -i -X POST
 * "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String append(String path, InputStream is)
        throws  IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();
    String spec = MessageFormat.format(
            "/webhdfs/v1/{0}?op=APPEND&user.name={1}",
            URLUtil.encodePath(path), this.principal);
    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL.openConnection(new URL(
            new URL(httpfsUrl), spec), token);
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, true);
        conn.disconnect();
    }

    return resp;
}
 
Example 17
Project: Nukkit-Java9   File: TimingsExport.java   Source Code and License Vote up 5 votes
@Override
public void run() {
    this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart"));
    this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export));

    String response = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("User-Agent", "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName());
        con.setRequestMethod("POST");
        con.setInstanceFollowRedirects(false);

        OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
            {
                this.def.setLevel(7);
            }
        };

        request.write(new Gson().toJson(this.out).getBytes("UTF-8"));
        request.close();

        response = getResponse(con);

        if (con.getResponseCode() != 302) {
            this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError", new String[]{String.valueOf(con.getResponseCode()), con.getResponseMessage()}));
            if (response != null) {
                Server.getInstance().getLogger().alert(response);
            }
            return;
        }

        String location = con.getHeaderField("Location");
        this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location));
        if (!(this.sender instanceof ConsoleCommandSender)) {
            Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location));
        }

        if (response != null && !response.isEmpty()) {
            Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsResponse", response));
        }

        File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings");
        timingFolder.mkdirs();
        String fileName = timingFolder + File.separator + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date());

        FileWriter writer = new FileWriter(fileName);
        writer.write(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location) + "\n\n");
        writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out));
        writer.close();

        Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsWrite", fileName));
    } catch (IOException exception) {
        this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError"));
        if (response != null) {
            Server.getInstance().getLogger().alert(response);
        }
        Server.getInstance().getLogger().logException(exception);
    }
}
 
Example 18
Project: ripme   File: DeviantartRipper.java   Source Code and License Vote up 5 votes
/**
 * If largest resolution for image at 'thumb' is found, starts downloading
 * and returns null.
 * If it finds a larger resolution on another page, returns the image URL.
 * @param thumb Thumbnail URL
 * @param page Page the thumbnail is retrieved from
 * @return Highest-resolution version of the image based on thumbnail URL and the page.
 */
private String smallToFull(String thumb, String page) {
    try {
        // Fetch the image page
        Response resp = Http.url(page)
                            .referrer(this.url)
                            .cookies(cookies)
                            .response();
        cookies.putAll(resp.cookies());
        Document doc = resp.parse();
        Elements els = doc.select("img.dev-content-full");
        String fsimage = null;
        // Get the largest resolution image on the page
        if (els.size() > 0) {
            // Large image
            fsimage = els.get(0).attr("src");
            logger.info("Found large-scale: " + fsimage);
            if (fsimage.contains("//orig")) {
                return fsimage;
            }
        }
        // Try to find the download button
        els = doc.select("a.dev-page-download");
        if (els.size() > 0) {
            // Full-size image
            String downloadLink = els.get(0).attr("href");
            logger.info("Found download button link: " + downloadLink);
            HttpURLConnection con = (HttpURLConnection) new URL(downloadLink).openConnection();
            con.setRequestProperty("Referer",this.url.toString());
            String cookieString = "";
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                cookieString = cookieString + entry.getKey() + "=" + entry.getValue() + "; ";
            }
            cookieString = cookieString.substring(0,cookieString.length() - 1);
            con.setRequestProperty("Cookie",cookieString);
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setInstanceFollowRedirects(true);
            con.connect();
            int code = con.getResponseCode();
            String location = con.getURL().toString();
            con.disconnect();
            if (location.contains("//orig")) {
                fsimage = location;
                logger.info("Found image download: " + location);
            }
        }
        if (fsimage != null) {
            return fsimage;
        }
        throw new IOException("No download page found");
    } catch (IOException ioe) {
        try {
            logger.info("Failed to get full size download image at " + page + " : '" + ioe.getMessage() + "'");
            String lessThanFull = thumbToFull(thumb, false);
            logger.info("Falling back to less-than-full-size image " + lessThanFull);
            return lessThanFull;
        } catch (Exception e) {
            return null;
        }
    }
}
 
Example 19
Project: NetCompile   File: FileHelper.java   Source Code and License Vote up 5 votes
public static String[] uploadEditorContent(TestSceneController controller) throws Exception
{
   String url = "http://danieloluwadare.com/write.php";
   url = "http://ec2-52-14-237-83.us-east-2.compute.amazonaws.com/write.php";
   //local
   url = "http://localhost/danielOluwadare.com/write.php";
   
   String charset = java.nio.charset.StandardCharsets.UTF_8.name();

   HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
   /*********************/
   /*
   school = "neiu";
   dept = "304-17";
   semester = "spr2017";
   test = "midterm";
   studentId = "265456";      
   */      

   String content = controller.getCode();
   String newContent = "";
   for( int i=0; i<content.length(); i++ ) 
   {
      if( content.charAt(i) == '+' ) 
         newContent += "%2B";
      else if( content.charAt(i) == '\t')
          newContent += "    ";
      else
         newContent += content.charAt(i);
   }

   String urlParameters  = "classID=" + controller.getCourse() + "&semester=" + controller.getSemester() + 
                  "&testDesc=" + controller.getTest() + "&studentID=" + controller.getStudentId() + 
                  "&school=" + controller.getSchool() + "&fileName=" + controller.getProblemName() + 
                  "&content=" + newContent;
   byte[] postData       = urlParameters.getBytes( java.nio.charset.StandardCharsets.UTF_8 );
   int    postDataLength = postData.length;
   String request        = url;
   URL    url2            = new URL( request );
   HttpURLConnection conn= (HttpURLConnection) url2.openConnection();           
   conn.setDoOutput( true );
   conn.setInstanceFollowRedirects( false );
   conn.setRequestMethod( "POST" );
   conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
   conn.setRequestProperty( "charset", "utf-8");
   conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
   conn.setUseCaches( false );
   try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
      wr.write( postData );
   }
   
   StringBuilder sb = new StringBuilder();  
   int HttpResult = conn.getResponseCode(); 
   if (HttpResult == HttpURLConnection.HTTP_OK) 
   {
      BufferedReader br = new BufferedReader(
         new InputStreamReader(conn.getInputStream(), "utf-8"));
      String line = null;  
      while ((line = br.readLine()) != null) 
      {  
         sb.append(line);  
      }
      br.close();
         
      String res = sb.toString();
      System.out.println(res);  

      res = res.replaceAll("\\[", "").replaceAll("\\]","");
      String[] retList = res.split(",", -1);
      
      return retList;
   }
   else 
   {
      System.out.println(conn.getResponseMessage());  
      return new String[0];
   }        
}
 
Example 20
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   Source Code and License Vote up 5 votes
/**
 * curl -i -X POST
 * "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=APPEND[&buffersize=<INT>]"
 *
 * @param path
 * @param is
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String append(String path, InputStream is)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    String redirectUrl = null;
    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=APPEND", path)), token);
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    logger.info("Location:" + conn.getHeaderField("Location"));
    resp = result(conn, true);
    if (conn.getResponseCode() == 307)
        redirectUrl = conn.getHeaderField("Location");
    conn.disconnect();

    if (redirectUrl != null) {
        conn = authenticatedURL.openConnection(new URL(redirectUrl), token);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Transfer-Encoding", "chunked");
        final int _SIZE = is.available();
        conn.setRequestProperty("Content-Length", "" + _SIZE);
        conn.setFixedLengthStreamingMode(_SIZE);
        conn.connect();
        OutputStream os = conn.getOutputStream();
        copy(is, os);
        // Util.copyStream(is, os);
        is.close();
        os.close();
        resp = result(conn, true);
        conn.disconnect();
    }

    return resp;
}