Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

public static boolean logout(String server_url) {

    if (isEmpty(server_url)) {
        Logd(TAG, "revokSite no server url");
        return false;
    }// w ww.j  a v  a2 s  . c o m

    if (!server_url.endsWith("/"))
        server_url += "/";

    // get end session endpoint
    String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url);
    if (isEmpty(end_session_endpoint)) {
        Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url);
        return false;
    }

    // set up connection
    HttpURLConnection huc = getHUC(end_session_endpoint);

    // TAZTAG test
    // huc.setInstanceFollowRedirects(false);
    huc.setInstanceFollowRedirects(true);
    // result : follows redirection is ok for taztag

    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setDoOutput(true);
    huc.setChunkedStreamingMode(0);
    // prepare parameters
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    try {
        // write parameters to http connection
        OutputStream os = huc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        // get URL encoded string from list of key value pairs
        String postParam = getQuery(nameValuePairs);
        Logd("Logout", "url: " + end_session_endpoint);
        Logd("Logout", "POST: " + postParam);
        writer.write(postParam);
        writer.flush();
        writer.close();
        os.close();

        // try to connect
        huc.connect();
        // connexion status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "Logout response: " + responseCode);
        // if 200 - OK
        if (responseCode == 200) {
            return true;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return false;
}

From source file:com.trimble.tekla.teamcity.HttpConnector.java

public void Post(TeamcityConfiguration conf, String url, Map<String, String> parameters) {

    try {// www .  j  a  v a2 s.com

        String urlstr = conf.getUrl() + url;

        URL urldata = new URL(urlstr);
        logger.warn("Hook Request: " + urlstr);

        String authStr = conf.getUserName() + ":" + conf.getPassWord();
        String authEncoded = Base64.encodeBase64String(authStr.getBytes());

        HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);

        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));

        StringBuilder dataout = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            dataout.append(line);
        }

        logger.warn("Hook Reply: " + line);

    } catch (Exception e) {
        logger.debug("Hook Exception: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:cz.vutbr.fit.xzelin15.dp.consumer.WSDynamicClientFactory.java

private String transferWSDL(String wsdlURL, String userPassword, WiseProperties wiseProperties)
        throws WiseConnectionException {
    String filePath = null;//from ww  w  .  j av a2 s . c  o m
    try {
        URL endpoint = new URL(wsdlURL);
        // Create the connection
        HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoOutput(false);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept",
                "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        // set Connection close, otherwise we get a keep-alive
        // connection
        // that gives us fragmented answers.
        conn.setRequestProperty("Connection", "close");
        // BASIC AUTH
        if (userPassword != null) {
            conn.setRequestProperty("Authorization",
                    "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes()));
        }
        // Read response
        InputStream is = null;
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            StringWriter sw = new StringWriter();
            char[] buf = new char[200];
            int read = 0;
            while (read != -1) {
                read = isr.read(buf);
                sw.write(buf);
            }
            throw new WiseConnectionException("Remote server's response is an error: " + sw.toString());
        }
        // saving file
        File file = new File(wiseProperties.getProperty("wise.tmpDir"),
                new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString());
        OutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        IOUtils.copyStream(fos, is);
        fos.close();
        is.close();
        filePath = file.getPath();
    } catch (WiseConnectionException wce) {
        throw wce;
    } catch (Exception e) {
        throw new WiseConnectionException("Wsdl download failed!", e);
    }
    return filePath;
}

From source file:gov.medicaid.verification.BaseSOAPClient.java

/**
 * Invokes the web service using the request provided.
 *
 * @param serviceURL the end point reference
 * @param original the payload/*from   w  ww  .j a v a 2  s.c  om*/
 * @return the response
 * @throws IOException for IO errors while executing the request
 * @throws TransformerException for any transformation errors
 */
protected String invoke(String serviceURL, String original) throws IOException, TransformerException {
    URL url = new URL(serviceURL);
    HttpURLConnection rc = (HttpURLConnection) url.openConnection();
    rc.setRequestMethod("POST");
    rc.setDoOutput(true);
    rc.setDoInput(true);
    rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

    System.out.println("before transform:" + original);
    String request = transform(requestXSLT, original);
    System.out.println("after transform:" + request);

    int len = request.length();
    rc.setRequestProperty("Content-Length", Integer.toString(len));
    rc.connect();
    OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream());
    out.write(request, 0, len);
    out.flush();

    InputStreamReader read;
    try {
        read = new InputStreamReader(rc.getInputStream());
    } catch (IOException e) {
        read = new InputStreamReader(rc.getErrorStream());
    }

    try {
        String response = IOUtils.toString(read);
        System.out.println("actual result:" + response);
        String transformedResponse = transform(responseXSLT, response);
        System.out.println("transformed result:" + transformedResponse);
        return transformedResponse;
    } finally {
        read.close();
        rc.disconnect();
    }
}

From source file:com.ejisto.modules.dao.remote.BaseRemoteDao.java

private HttpURLConnection openConnection(String requestPath, String method) throws IOException {
    String destination = serverAddress + defaultIfEmpty(requestPath, "/");
    log.log(Level.FINEST, "url destination: " + destination);
    HttpURLConnection connection = (HttpURLConnection) new URL(destination).openConnection();
    connection.setDoInput(true);//from w  w w  .j a  v  a  2s . c o m
    connection.setDoOutput(true);
    if (method != null) {
        connection.setRequestMethod(method.toUpperCase());
    }
    connection.connect();
    return connection;
}

From source file:com.gliffy.restunit.http.JavaHttp.java

/** Performs an HTTP PUT. 
 * @param request the request describing the PUT.
 * @return a response//from   w  ww.j  a v a  2s  . co  m
 * @throws IOException if HttpURLConnection generated an IO Exception
 */
public HttpResponse put(HttpRequest request) throws IOException {
    HttpURLConnection connection = getConnection(request);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.connect();
    setBody(request, connection);
    HttpResponse response = createResponse(connection);
    connection.disconnect();
    return response;
}

From source file:com.trimble.tekla.teamcity.HttpConnector.java

public void PostPayload(TeamcityConfiguration conf, String url, String payload) {

    try {//  w  ww .j  a  va 2 s.com

        String urlstr = conf.getUrl() + url;

        URL urldata = new URL(urlstr);
        logger.warn("Hook Request: " + urlstr);

        String authStr = conf.getUserName() + ":" + conf.getPassWord();
        String authEncoded = Base64.encodeBase64String(authStr.getBytes());

        HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);

        if (payload != null) {
            connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
            connection.setRequestProperty("Content-Length", Integer.toString(payload.length()));
            connection.getOutputStream().write(payload.getBytes("UTF8"));
        }

        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));

        StringBuilder dataout = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            dataout.append(line);
        }

        logger.warn("Hook Reply: " + line);

    } catch (Exception e) {
        logger.debug("Hook Exception: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

/**
 * Post data//w  w  w.  ja  va 2  s .c om
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:com.gliffy.restunit.http.JavaHttp.java

/** Performs an HTTP POST.
 * @param request the request describing the POST.
 * @return a response/*from   w  ww.jav  a  2 s . co m*/
 * @throws IOException if HttpURLConnection generated an IO Exception
 */
public HttpResponse post(HttpRequest request) throws IOException {
    HttpURLConnection connection = getConnection(request);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.connect();
    setBody(request, connection);
    HttpResponse response = createResponse(connection);
    connection.disconnect();
    return response;
}

From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java

@Override
public HashSet<Tag> solveC2W(String text) throws AnnotationException {
    lastTime = Calendar.getInstance().getTimeInMillis();
    HashSet<Tag> res = new HashSet<Tag>();
    try {/* www .  ja  va2  s . com*/
        URL erdApi = new URL(url);

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

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        multipartEntity.addPart("runID", new StringBody(this.run));
        multipartEntity.addPart("TextID", new StringBody("" + text.hashCode()));
        multipartEntity.addPart("Text", new StringBody(text));

        connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
        OutputStream out = connection.getOutputStream();
        try {
            multipartEntity.writeTo(out);
        } finally {
            out.close();
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        if (status != 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                System.err.println(line);
            throw new RuntimeException();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            String mid = line.split("\t")[2];
            String title = freebApi.midToTitle(mid);
            int wid;
            if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1)
                System.err.println("Discarding mid=" + mid);
            else
                res.add(new Tag(wid));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    return res;
}