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.jug6ernaut.android.utilites.FileDownloader.java

public File downloadFile(String serverUrl, String fileToFetch, File outputFile) throws IOException {
    //File outputFile = null;

    String urlToFetch = serverUrl + fileToFetch;
    URL url = new URL(urlToFetch);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();//  w  w w.ja v  a  2  s  . c o  m

    File dir = outputFile.getParentFile();
    dir.mkdirs();

    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ((len1 = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len1);
    }
    fos.close();
    is.close();

    //pd.dismiss();
    return outputFile;
}

From source file:com.intravel.Facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//from  w w w .ja v  a2s. c o m
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    //        else{
    //            url = url + "&" + encodeUrl(params);
    //        }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test method for.//  w  ww .ja va 2 s.c  o  m
 *
 * @throws Exception the exception
 * {@link ext.services.network.NetworkUtils#readPostURL(java.net.HttpURLConnection, java.lang.String)}
 * .
 */
public void testReadPostURL() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    connection.setDoOutput(true);
    // TODO: currently I do not have an URL that works via POST, therefore we
    // get an invalid return code
    try {
        NetworkUtils.readPostURL(connection, "post");
        fail("Currently fails here");
    } catch (IllegalArgumentException e) {
        assertTrue(e.getMessage(), e.getMessage().contains("Invalid HTTP return code"));
    }
    connection.disconnect();
}

From source file:dj.comprobantes.offline.service.CPanelServiceImp.java

@Override
public void reenviarComprobante(String correo, Long id) throws GenericException {
    Map<String, Object> params = new LinkedHashMap<>();
    params.put("PK_CODIGO_COMP", id);
    params.put("CORREO_USUARIO", correo);
    StringBuilder postData = new StringBuilder();
    try {//from   ww w. j a v a 2s .  c  o m
        URL url = new URL(ParametrosSistemaEnum.CPANEL_WEB_REENVIAR.getCodigo());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Accept", "application/json;odata=verbose");
        conn.setRequestProperty("Authorization", "AccesToken");
        postData.append("{");
        for (Map.Entry<String, Object> param : params.entrySet()) {
            if (postData.length() != 1) {
                postData.append(',');
            }
            postData.append("\"").append(param.getKey()).append("\"");
            postData.append(":\"");
            postData.append(String.valueOf(param.getValue())).append("\"");
        }
        postData.append("}");
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(postDataBytes);
        os.flush();
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();
    } catch (IOException | RuntimeException e) {
        throw new GenericException(e);
    }

}

From source file:io.github.retz.web.NoAuthWebConsoleTest.java

@Test
public void status() throws Exception {
    Application app = new Application("fooapp", Arrays.asList(), Arrays.asList(), Arrays.asList(),
            Optional.empty(), Optional.empty(), config.getUser().keyId(), new MesosContainer(), true);
    Database.getInstance().addApplication(app);
    Job job = new Job(app.getAppid(), "foocmd", null, 12000, 12000);
    JobQueue.push(job);//from  w ww  .  ja v  a 2s. c  om

    URL url = new URL(config.getUri().toASCIIString() + "/status");
    System.err.println(url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoOutput(true);
    Response res = mapper.readValue(conn.getInputStream(), Response.class);
    assertThat(res, instanceOf(StatusResponse.class));
    StatusResponse statusResponse = (StatusResponse) res;

    System.err.println(statusResponse.queueLength());
    assertThat(statusResponse.queueLength(), is(1));
    assertThat(statusResponse.sessionLength(), is(0));
}

From source file:com.example.rtobase2.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;//from   ww  w .java2 s  .  co  m
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }

            if (request instanceof PUT) {
                byte[] payload = ((PUT) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                conn.setRequestMethod("PUT");
                JSONObject jsonobj = getJSONObject(s);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();
            }

            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {

                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.skplanet.syruppay.client.SyrupPayClientTest.java

@Test
public void testGet_Sso_WITH_BASIC_AUTHENTICATION() throws IOException {
    URL url = new URL(
            "https://devqapay.syrup.co.kr/v1/api-basic/merchants/sktmall_s002/sso-credentials/create");

    String encoding = org.apache.commons.codec.binary.Base64
            .encodeBase64String("sktmall_s002:W9n7yLQrpt2Sm1zpqFpxr9k95BWNRXxs".getBytes());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.setRequestProperty("Accept", "application/jose");
    connection.setRequestProperty("Content-type", "application/jose");

    JoseHeader h = new JoseHeader(Jwa.A128KW, Jwa.A128CBC_HS256, "sktmall_s001");
    String request = new Jose().configuration(JoseBuilders
            .JsonEncryptionCompactSerializationBuilder().header(h).payload("{\n" + "    \"ssoIdentifier\": {\n"
                    + "        \"mctUserId\" : \"15644623-3\"\n" + "    }\n" + "}")
            .key("G3aIW7hYmlTjag3FDc63OGLNWwvagVUU")).serialization();

    OutputStream out = connection.getOutputStream();
    out.write(request.getBytes());//from   w  ww .  jav a 2s .com
    out.close();

    try {
        int status = connection.getResponseCode();
        InputStream content;
        if (status == 200) {
            content = connection.getInputStream();
        } else {
            content = connection.getErrorStream();
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line;
        StringBuilder buf = new StringBuilder();
        while ((line = in.readLine()) != null) {
            buf.append(line);
        }

        String response = new Jose().configuration(JoseBuilders.compactDeserializationBuilder()
                .serializedSource(buf.toString()).key("G3aIW7hYmlTjag3FDc63OGLNWwvagVUU")).deserialization();

        System.out.println(response);

        in.close();
    } catch (FileNotFoundException fe) {
        // ? ?
        System.out.println("User Not Found");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.bashtech.geobot.BotManager.java

public static String postCoebotVars(String postData, String requestURL) {
    if (BotManager.getInstance().CoeBotTVAPIKey.length() > 4) {
        URL url;//  w  ww .java2s.  c o m
        HttpURLConnection conn;

        try {
            url = new URL(requestURL + "$" + BotManager.getInstance().CoeBotTVAPIKey + "$"
                    + BotManager.getInstance().nick);

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", "CoeBot");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

            // conn.setConnectTimeout(5 * 1000);
            // conn.setReadTimeout(5 * 1000);

            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(postData);
            out.close();

            String response = "";

            Scanner inStream = new Scanner(conn.getInputStream());

            while (inStream.hasNextLine())
                response += (inStream.nextLine());

            inStream.close();
            return response;

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return "";
    } else
        return "";
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Sends request to Equifax./*from w  w w. j a  v a  2s .  co  m*/
 * @param server {@link String}
 * @param send {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
public String sendToEquifax(final String server, final String send) throws IOException {

    String params = "InputSegments=" + URLEncoder.encode(send, "UTF-8") + "&cmdSubmit=Submit";

    byte[] postData = params.getBytes(StandardCharsets.UTF_8);
    int postDataLength = postData.length;

    URL url = new URL(server);
    HttpURLConnection conn = (HttpURLConnection) url.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);

    Reader in = null;
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);

        StringBuilder sb = new StringBuilder();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c = in.read(); c != -1; c = in.read()) {
            sb.append((char) c);
        }

        String receive = sb.toString();

        return receive;

    } finally {

        if (in != null) {
            in.close();
        }

        if (wr != null) {
            wr.close();
        }
    }
}