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.android.volley.toolbox.http.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.getBody();
        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.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*  ww w .ja v  a 2  s .c  o  m*/
            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:com.example.appengine.UrlFetchServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    String id = req.getParameter("id");
    String text = req.getParameter("text");

    if (id == null || text == null || id == "" || text == "") {
        req.setAttribute("error", "invalid input");
        req.getRequestDispatcher("/main.jsp").forward(req, resp);
        return;//from  w ww  .  j  av a 2  s  .com
    }

    JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text);

    // [START complex]
    URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
    writer.close();

    int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
    if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
        req.setAttribute("error", "");
        StringBuffer response = new StringBuffer();
        String line;

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        req.setAttribute("response", response.toString());
    } else {
        req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    // [END complex]
    req.getRequestDispatcher("/main.jsp").forward(req, resp);
}

From source file:jcine.AsientosClient.java

public Asiento[] getAsientos() throws IOException, ParseException {

    HttpURLConnection conn = (HttpURLConnection) entryPoint.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoOutput(true);
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    String line;/*from  w  ww  .  j  a v  a2 s  .  co m*/
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    JSONParser parser = new JSONParser();

    JSONArray list = (JSONArray) parser.parse(builder.toString());

    Asiento[] result = new Asiento[list.size()];

    for (int i = 0; i < list.size(); i++) {
        JSONObject obj = (JSONObject) list.get(i);
        String name = (String) obj.get("numero");
        Long posX = (Long) obj.get("posicionX");
        Long posY = (Long) obj.get("posicionY");

        result[i] = new Asiento(name, posX.intValue(), posY.intValue());

    }

    return result;
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Send a file via HTTP POST with basic authentication.
 *
 * @param context  the context to use.//from  w  w  w .  j a  v  a  2  s  . c  o  m
 * @param urlStr   the server url to POST to.
 * @param file     the file to send.
 * @param user     the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the return string from the POST.
 * @throws Exception if something goes wrong.
 */
public static String sendFilePost(Context context, String urlStr, File file, String user, String password)
        throws Exception {
    BufferedOutputStream wr = null;
    FileInputStream fis = null;
    HttpURLConnection conn = null;
    try {
        fis = new FileInputStream(file);
        long fileSize = file.length();
        // Authenticator.setDefault(new Authenticator(){
        // protected PasswordAuthentication getPasswordAuthentication() {
        // return new PasswordAuthentication("test", "test".toCharArray());
        // }
        // });
        urlStr = urlStr + "?name=" + file.getName();
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(true);

        // conn.setRequestProperty("Accept-Encoding", "gzip ");
        // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        // conn.setRequestProperty("Content-Length", "" + fileSize);
        // conn.setRequestProperty("Connection", "Keep-Alive");

        if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        wr = new BufferedOutputStream(conn.getOutputStream());
        long bufferSize = Math.min(fileSize, maxBufferSize);

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize);
        byte[] buffer = new byte[(int) bufferSize];
        int bytesRead = fis.read(buffer, 0, (int) bufferSize);
        long totalBytesWritten = 0;
        while (bytesRead > 0) {
            wr.write(buffer, 0, (int) bufferSize);
            totalBytesWritten = totalBytesWritten + bufferSize;
            if (totalBytesWritten >= fileSize)
                break;

            bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize);
            bytesRead = fis.read(buffer, 0, (int) bufferSize);
        }
        wr.flush();

        int responseCode = conn.getResponseCode();
        return getMessageForCode(context, responseCode,
                context.getResources().getString(R.string.file_upload_completed_properly));

    } catch (Exception e) {
        throw e;
    } finally {
        if (wr != null)
            wr.close();
        if (fis != null)
            fis.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:net.terryyiu.emailservice.providers.AbstractEmailServiceProvider.java

private HttpURLConnection createConnection() throws IOException {
    URL url = new URL(getServiceUrl());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);/*from   w  ww.  ja v  a2 s  . c  o  m*/
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);

    modifyConnection(connection);

    return connection;
}

From source file:com.example.appengine.java8.LaunchDataflowTemplate.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String project = "YOUR_PROJECT_NAME";
    String bucket = "gs://YOUR_BUCKET_NAME";

    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/cloud-platform");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);

    JSONObject jsonObj = null;/*w w w.j  a v  a 2s .  c o  m*/
    try {
        JSONObject parameters = new JSONObject().put("datastoreReadGqlQuery", "SELECT * FROM Entries")
                .put("datastoreReadProjectId", project).put("textWritePrefix", bucket + "/output/");
        JSONObject environment = new JSONObject().put("tempLocation", bucket + "/tmp/")
                .put("bypassTempDirValidation", false);
        jsonObj = new JSONObject().put("jobName", "template-" + UUID.randomUUID().toString())
                .put("parameters", parameters).put("environment", environment);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = new URL(String.format("https://dataflow.googleapis.com/v1b3/projects/%s/templates"
            + ":launch?gcs_path=gs://dataflow-templates/latest/Datastore_to_GCS_Text", project));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    jsonObj.write(writer);
    writer.close();

    int respCode = conn.getResponseCode();
    if (respCode == HttpURLConnection.HTTP_OK) {
        response.setContentType("application/json");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.getWriter().println(line);
        }
        reader.close();

    } else {
        StringWriter w = new StringWriter();
        IOUtils.copy(conn.getErrorStream(), w, "UTF-8");
        response.getWriter().println(w.toString());
    }
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

protected static void uploadFile(String locationFilename, String saveFilename) {
    System.out.println("saving " + locationFilename + "!! ");
    if (!saveFilename.contains("."))
        saveFilename = saveFilename + Utilities.getExtension(locationFilename);

    if (!fileExistsOnServer(saveFilename)) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = locationFilename;
        String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php";
        //         String urlServer = "http://timelinegamified.appspot.com/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;

        try {// w w  w . j a  v a 2 s  . com
            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + saveFilename + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage);
        } catch (Exception ex) {
            //Exception handling
        }
    } else {
        System.out.println("image exists on server");
    }
}

From source file:org.apache.taverna.activities.interaction.InteractionUtils.java

void publishFile(final String urlString, final InputStream is, final String runId, final String interactionId)
        throws IOException {
    if (InteractionUtils.publishedUrls.contains(urlString)) {
        return;//from   w w  w .  j  a v  a  2s.c o  m
    }
    InteractionUtils.publishedUrls.add(urlString);
    if (runId != null) {
        interactionRecorder.addResource(runId, interactionId, urlString);
    }

    final URL url = new URL(urlString);
    final HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("PUT");
    final OutputStream outputStream = httpCon.getOutputStream();
    IOUtils.copy(is, outputStream);
    is.close();
    outputStream.close();
    int code = httpCon.getResponseCode();
    if ((code >= 400) || (code < 0)) {
        throw new IOException("Received code " + code);
    }
}

From source file:com.acc.util.InstagramClient.java

public String getProfilePicOfUser(final String code) {

    String profilePic = null;/*from ww  w.  j  av  a  2s.com*/
    //      final String inputJson = "client_id=e580d04d0687403189f86d49545b69a4&client_secret=a2943297f601402d894f8d21400bdfd5&grant_type=authorization_code&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage&code="
    //            + code;

    //String inputJson1 = "{\"Identities\": [{\"Score\": \"99.99986\",\"IdentityDetails\": {\"BiographicData\": [{\"Key\": \"Name\",\"Value\": \"Ravi\"},{\"Key\": \"ID\",\"Value\": \"DRIVING_LICENSE_ID\"}],\"BiometricDatas\": [{\"Base64Data\": \"/9j/4AAQSkZJ\",\"Modality\": \"Face_Face2D\",\"Type\": \"Image\"}],\"IdentityId\": \"BiometricDev[1:S:58840];\"}}],\"InWatchList\": false}";
    //      System.out.println(inputJson);

    // Make Web Service Call

    //      final Client client = ClientBuilder.newClient();
    //      final String instagramOutputJson = client.target("https://api.instagram.com/oauth/access_token").request()
    //            .method("POST", Entity.entity(inputJson, MediaType.APPLICATION_JSON), String.class);

    try {
        final URL url = new URL("https://api.instagram.com/oauth/access_token");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        final String urlParameters = "client_id=e580d04d0687403189f86d49545b69a4"
                + "&client_secret=a2943297f601402d894f8d21400bdfd5" + "&grant_type=authorization_code"
                + "&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage"
                + "&code=" + code;

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        final BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result.toString());
        System.out.println("Output Json from Instagram is " + result);
        profilePic = processJson(result.toString());
    } catch (final MalformedURLException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    }
    return profilePic;

}

From source file:technology.tikal.accounts.dao.rest.SessionDaoRest.java

private void guardar(UserSession objeto, int intento) {
    //basic auth string
    String basicAuthString = config.getUser() + ":" + config.getPassword();
    basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes()));
    basicAuthString = "Basic " + basicAuthString;

    //mensaje remoto
    try {//  ww w  .  j  av a  2 s.  c o m
        //config
        URL url = new URL(config.getUrl());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(config.getMethod());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", basicAuthString);
        connection.setInstanceFollowRedirects(false);
        //write
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(mapper.writeValueAsString(objeto));
        //close
        writer.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            return;
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationRefused.SessionDaoRest.guardar" },
                    new String[] { connection.getResponseCode() + "" }, ""));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        if (intento <= maxRetry) {
            this.guardar(objeto, intento + 1);
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationError.SessionDaoRest.guardar" },
                    new String[] { e.getMessage() }, ""));
        }
    }
}