Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Prototype

int HTTP_UNAUTHORIZED

To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:OCRRestAPI.java

public static void main(String[] args) throws Exception {
    /*//from  ww  w.  j a v a2  s .  co m
              
         Sample project for OCRWebService.com (REST API).
         Extract text from scanned images and convert into editable formats.
         Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code
            
     */

    // Provide your user name and license code
    String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D";
    String user_name = "FERGOID";

    /*
            
      You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide
             
      Input parameters:
             
     [language]      - Specifies the recognition language. 
                  This parameter can contain several language names separated with commas. 
                    For example "language=english,german,spanish".
               Optional parameter. By default:english
            
     [pagerange]     - Enter page numbers and/or page ranges separated by commas. 
               For example "pagerange=1,3,5-12" or "pagerange=allpages".
                    Optional parameter. By default:allpages
             
      [tobw]           - Convert image to black and white (recommend for color image and photo). 
               For example "tobw=false"
                    Optional parameter. By default:false
             
      [zone]          - Specifies the region on the image for zonal OCR. 
               The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. 
               This parameter can contain several zones separated with commas. 
                 For example "zone=0:0:100:100,50:50:50:50"
                    Optional parameter.
              
      [outputformat]  - Specifies the output file format.
                    Can be specified up to two output formats, separated with commas.
               For example "outputformat=pdf,txt"
                    Optional parameter. By default:doc
            
      [gettext]      - Specifies that extracted text will be returned.
               For example "tobw=true"
                    Optional parameter. By default:false
            
       [description]  - Specifies your task description. Will be returned in response.
                    Optional parameter. 
            
            
     !!!!  For getting result you must specify "gettext" or "outputformat" !!!!  
            
    */

    // Build your OCR:

    // Extraction text with English language
    String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";

    // Extraction text with English and German language using zonal OCR
    ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400";

    // Convert first 5 pages of multipage document into doc and txt
    // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt";

    // Full path to uploaded document
    String filePath = "sarah-morgan.jpg";

    byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

    URL url = new URL(ocrURL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));

    // Specify Response format to JSON or XML (application/json or application/xml)
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

    int httpCode;
    try (OutputStream stream = connection.getOutputStream()) {

        // Send POST request
        stream.write(fileContent);
        stream.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    httpCode = connection.getResponseCode();

    System.out.println("HTTP Response code: " + httpCode);

    // Success request
    if (httpCode == HttpURLConnection.HTTP_OK) {
        // Get response stream
        String jsonResponse = GetResponseToString(connection.getInputStream());

        // Parse and print response from OCR server
        PrintOCRResponse(jsonResponse);
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        System.out.println("OCR Error Message: Unauthorizied request");
    } else {
        // Error occurred
        String jsonResponse = GetResponseToString(connection.getErrorStream());

        JSONParser parser = new JSONParser();
        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

        // Error message
        System.out.println("Error Message: " + jsonObj.get("ErrorMessage"));
    }

    connection.disconnect();

}

From source file:fr.ms.tomcat.manager.TomcatManagerUrl.java

public static String appelUrl(final URL url, final String username, final String password,
        final String charset) {

    try {/*from w w  w. jav a 2  s.  c om*/
        final URLConnection urlTomcatConnection = url.openConnection();

        final HttpURLConnection connection = (HttpURLConnection) urlTomcatConnection;

        LOG.debug("url : " + url);
        connection.setAllowUserInteraction(false);
        connection.setDoInput(true);
        connection.setUseCaches(false);

        connection.setDoOutput(false);
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Authorization", toAuthorization(username, password));

        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new TomcatManagerException("Reponse http : " + connection.getResponseMessage()
                        + " - Les droits \"manager\" ne sont pas appliques - utilisateur : \"" + username
                        + "\" password : \"" + password + "\"");
            }
            throw new TomcatManagerException("HttpURLConnection.HTTP_UNAUTHORIZED");
        }

        final String response = toString(connection.getInputStream(), charset);

        LOG.debug("reponse : " + response);

        return response;
    } catch (final Exception e) {
        throw new TomcatManagerException("L'url du manager tomcat est peut etre incorrecte : \"" + url + "\"",
                e);
    }
}

From source file:info.FlixBusDemo.volley.NetworkResponse.java

public NetworkResponse(byte[] data) {
    this(HttpURLConnection.HTTP_UNAUTHORIZED, data, Collections.<String, String>emptyMap(), false, 0);
}

From source file:com.ls.util.internal.VolleyResponseUtils.java

public static boolean isAuthError(VolleyError volleyError) {
    return volleyError != null && volleyError.networkResponse != null
            && volleyError.networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED;
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.errors.BodhiClientLoginException.java

/**
 * //from w ww.j  av a2s.c  o m
 * @return {@code true} if the user was not allowed access (i.e. 403,
 *         Forbidden was returned).
 */
public boolean isInvalidCredentials() {
    // Comment from: [...]fedora/client/proxyclient.py
    // Check for auth failures
    // Note: old TG apps returned 403 Forbidden on authentication failures.
    // Updated apps return 401 Unauthorized
    // We need to accept both until all apps are updated to return 401.
    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode == HttpURLConnection.HTTP_FORBIDDEN
            || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        // wrong username or password
        return true;
    }
    // some other, perhaps inconclusive? error
    return false;
}

From source file:com.mobile.godot.core.controller.LoginController.java

public synchronized void login(LoginBean login) {

    String servlet = "Login";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", login.getUsername()));
    params.add(new BasicNameValuePair("password", login.getPassword()));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Session.LOGGED_IN);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Session.NOT_LOGGED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*from w  w  w .  j a v  a  2 s .  co  m*/

}

From source file:com.utest.webservice.auth.BasicAuthAuthorizationInterceptor.java

@Override
public void handleMessage(final Message message) throws Fault {
    try {//from w  w w.  j  a  va 2 s  .c o m
        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        Authentication authentication = SessionUtil.getAuthenticationToken(message);
        if (policy == null && authentication == null) {
            sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
            return;
        }
        if (authentication == null) {
            authentication = new UsernamePasswordAuthenticationToken(policy.getUserName(),
                    policy.getPassword());
            ((UsernamePasswordAuthenticationToken) authentication).setDetails(message.get("HTTP.REQUEST"));
            authentication = authenticationProvider.authenticate(authentication);
        } else {
            if (((UsernamePasswordAuthenticationToken) authentication).getDetails() == null) {
                ((UsernamePasswordAuthenticationToken) authentication).setDetails(message.get("HTTP.REQUEST"));
            }
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (final RuntimeException ex) {
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
        throw ex;
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.GerritPluginChecker.java

/**
 * Given a status code, decode its status.
 * @param statusCode HTTP code//from   w ww  .  jav  a2s. c o  m
 * @param pluginName plugin that was checked.
 * @return true/false if installed or not.
 */
private static boolean decodeStatus(int statusCode, String pluginName) {
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
        logger.info(Messages.PluginInstalled(pluginName));
        return true;
    case HttpURLConnection.HTTP_NOT_FOUND:
        logger.info(Messages.PluginNotInstalled(pluginName));
        return false;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        logger.warn(
                Messages.PluginHttpConnectionUnauthorized(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    case HttpURLConnection.HTTP_FORBIDDEN:
        logger.warn(Messages.PluginHttpConnectionForbidden(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    default:
        logger.warn(Messages.PluginHttpConnectionGeneralError(pluginName,
                Messages.HttpConnectionError(statusCode)));
        return false;
    }
}

From source file:org.apache.geronimo.testsuite.security.test.GenericRealmTest.java

/**
 * Test 4  /*from w w w .ja v  a 2s.c om*/
 * Test invalid user "nobody" cannot access the protected resources
 */
@Test
public void GenericUnauthTest() throws Exception {
    Assert.assertEquals(getHTTPResponseStatus("nobody"), HttpURLConnection.HTTP_UNAUTHORIZED);
}

From source file:org.peterbaldwin.vlcremote.net.ServerConnectionTest.java

@Override
protected void onPostExecute(Integer result) {
    switch (result) {
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        Toast.makeText(context, R.string.server_unauthorized, Toast.LENGTH_SHORT).show();
        break;//from w  ww .  j  a  v a2s.  c om
    case HttpURLConnection.HTTP_FORBIDDEN:
        Toast.makeText(context, R.string.server_forbidden, Toast.LENGTH_SHORT).show();
        break;
    case HttpURLConnection.HTTP_OK:
        Toast.makeText(context, R.string.server_ok, Toast.LENGTH_SHORT).show();
        break;
    default:
        Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show();
    }
}