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.synelixis.xifi.AuthWebClient.Client.java

private String postURL(String url_, String data_, String credentials_) {
    String urlString = url_;//  w ww.  j  av a  2 s .co m
    String JSON = data_;
    String credentials = credentials_;

    try {
        URL u = new URL(urlString);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        if ((credentials != null) && !credentials.equals("")) {
            c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            c.setRequestProperty("Authorization", "Basic " + credentials);
        } else {
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Accept", "application/json");
        }
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write(JSON);
        out.flush();
        out.close();
        System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode());
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            String result = sb.toString();
            return result;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE,
                "Unexpected exception when call the remote server ", ex);
    }
    return null;
}

From source file:it.avalz.opendaylight.controller.Controller.java

public void addFlow(Flow f) {
    Vertex v = f.getNode();//from   w w  w. j  a  va2  s.c  om

    String authString = this.username + ":" + this.password;

    try {
        StringBuilder urlString = new StringBuilder();

        urlString.append(this.baseUrl).append("/flowprogrammer/default/node/OF/").append(v.getId())
                .append("/staticFlow/").append(f.getName());
        URL url = new URL(urlString.toString());
        byte[] authEncoded = Base64.encodeBase64(authString.getBytes());
        String authEncodedString = new String(authEncoded);

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

        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        connection.setRequestProperty("Authorization", "Basic " + authEncodedString);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

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

        out.write(f.toString());
        out.close();

        connection.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Flow installed on vertex " + v);
    System.out.println(f);
}

From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java

/**
 * Executes a multipart form upload to the S3 Bucket as described in
 * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>.
 * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever
 *                               bytes are written to the outgoing connection. May be null.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 *///from   ww w . j  a va 2s.co m
public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener)
        throws IOException, ClientProtocolException {
    //unfortunately, we can't use Unirest to execute the call, because there is no support
    //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26

    int bufferSize = 1024;

    //opening a connection to the S3 Bucket
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection();
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setChunkedStreamingMode(bufferSize);
    urlConnection.setRequestProperty("Connection", "Keep-Alive");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    String boundary = "*****";
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    //writing the request headers
    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

    String newline = "\r\n";
    String twoHyphens = "--";
    dos.writeBytes(twoHyphens + boundary + newline);

    String attachmentName = "file";
    String attachmentFileName = "file";

    dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
            + attachmentFileName + "\"" + newline);
    dos.writeBytes(newline);

    //sending the actual file
    byte[] buf = new byte[bufferSize];

    FileInputStream fis = new FileInputStream(file);
    long totalBytes = fis.getChannel().size();
    long writtenBytes = 0;

    int len;
    while ((len = fis.read(buf)) != -1) {
        dos.write(buf);
        writtenBytes += len;

        s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes,
                (float) ((double) writtenBytes / totalBytes)));

        if (interrupt) {
            fis.close();
            dos.close();
            return;
        }
    }

    fis.close();

    //finish the call
    dos.writeBytes(newline);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + newline);

    dos.close();

    urlConnection.disconnect();
}

From source file:imdbdataextract.IMDBDataExtract.java

public String Login(String url) throws MalformedURLException, IOException {
    try {/* ww  w .j a  va2 s .  c  om*/
        //this.BaseUrl = "https://api.themoviedb.org/3/movie/"+str+"?api_key=ff952840f45b98d699b51692ac712cdd";
        //this.BaseUrl="https://api.themoviedb.org/3/genre/movie/list?api_key=ff952840f45b98d699b51692ac712cdd&language=en-US";
        this.BaseUrl = url;
        //this.BaseUrl="http://api.themoviedb.org/3/movie/"+str+"/videos?api_key=ff952840f45b98d699b51692ac712cdd";
        HttpURLConnection httpcon = (HttpURLConnection) ((new URL(BaseUrl).openConnection()));
        httpcon.setDoOutput(true);
        httpcon.connect();
        BufferedReader inreader = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = inreader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return "";
    }

}

From source file:cn.ctyun.amazonaws.internal.EC2MetadataClient.java

/**
 * Connects to the metadata service to read the specified resource and
 * returns the text contents./*ww w  . j ava 2 s. c  o m*/
 *
 * @param resourcePath
 *            The resource
 *
 * @return The text payload returned from the Amazon EC2 Instance Metadata
 *         service for the specified resource path.
 *
 * @throws IOException
 *             If any problems were encountered while connecting to metadata
 *             service for the requested resource path.
 * @throws AmazonClientException
 *             If the requested metadata service is not found.
 */
public String readResource(String resourcePath) throws IOException, AmazonClientException {
    URL url = getEc2MetadataServiceUrlForResource(resourcePath);
    log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(1000 * 2);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();

    return readResponse(connection);
}

From source file:org.wisdom.openid.connect.request.UserInfoRequest.java

public UserInfoResponse execute() throws IOException {

    HttpURLConnection connection = (HttpURLConnection) userInfoEndpoint.openConnection();
    connection.addRequestProperty("Authorization", format("Bearer %s", accessToken));

    connection.setUseCaches(false);//w ww.j  a v a 2s . c o m
    connection.setDoInput(true);
    connection.setDoOutput(true);

    //Get Response
    JsonNode node = new ObjectMapper().readTree(connection.getInputStream());
    return new UserInfoResponse(node.get("sub").asText(), node);

}

From source file:com.androidex.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);// w w  w  .  ja  v a 2 s .com
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        // connection.setRequestMethod("PATCH");
        // If server doesnt support patch uncomment this
        connection.setRequestMethod("POST");
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:de.thingweb.discovery.TDRepository.java

/**
 * Update existing TD//  w w w .j  av  a 2s. c  om
 * 
 * @param key in repository (/td/{id})
 * @param content JSON-LD
 * @throws Exception in case of error
 */
public void updateTD(String key, byte[] content) throws Exception {
    URL url = new URL("http://" + repository_uri + key);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestProperty("content-type", "application/ld+json");
    httpCon.setRequestMethod("PUT");
    OutputStream out = httpCon.getOutputStream();
    out.write(content);
    out.close();

    //      InputStream is = httpCon.getInputStream();
    //      ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //      int b;
    //      while ((b = is.read()) != -1) {
    //         baos.write(b);
    //      }

    int responseCode = httpCon.getResponseCode();

    httpCon.disconnect();

    if (responseCode != 200) {
        // error
        throw new RuntimeException("ResponseCodeError: " + responseCode);
    }
}

From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java

private String query(String method, String op, Object... args) {
    String url = this.curatorurl + this.service + op;
    try {/*from w w  w  .  j  a  va 2s.  c o m*/
        String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8");
        for (int i = 0; i < args.length; i += 2) {
            params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }

        URL urlobj = new URL(url);
        if ("GET".equals(method))
            urlobj = new URL(url + "?" + params);
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod(method);
        if (!"GET".equals(method)) {
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();
        }

        String result = IOUtils.toString(con.getInputStream());
        con.disconnect();
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.kinvey.business_logic.collection_access.MongoRequest.java

private HttpResponse makeRequest() throws CollectionAccessException {
    KinveyAuthCredentials authCredentials = KinveyAuthCredentials.getInstance();

    try {/*from   w  w  w . ja v a  2s. co m*/
        String encodedUrl = this.protocol + "://" + this.baseUrl + "/" + authCredentials.getAppId() + "/"
                + this.collection.collectionName + "/" + this.collectionOperation.getEndPoint();

        String userPass = authCredentials.getAppId() + ":" + authCredentials.getMasterSecret();
        String authString = "Basic " + new String(Base64.encode(userPass), "UTF-8");

        URL url = new URL(encodedUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", authString);

        String input = buildBody();

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String tmpOutput;
        String contentBody = "";
        while ((tmpOutput = br.readLine()) != null) {
            contentBody += tmpOutput;
        }
        conn.disconnect();

        HttpResponse response = new HttpResponse(contentBody);

        return response;

    } catch (IOException e) {
        throw new CollectionAccessException(e);
    }
}