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.zf.util.Post_NetNew.java

/**
 * ?/*from  ww  w.j  a v  a  2  s  .  c  om*/
 * 
 * @param pams
 * @param ip
 * @param port
 * @return
 * @throws Exception
 */
public static String pn(Map<String, String> pams, String ip, int port) throws Exception {
    if (null == pams) {
        return "";
    }
    InetSocketAddress addr = new InetSocketAddress(ip, port);
    Proxy proxy = new Proxy(Type.HTTP, addr);
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
    httpConn.setConnectTimeout(30000);
    httpConn.setReadTimeout(30000);
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;/*from w  w w  . j a  va  2  s.c  om*/

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset/*from ww  w. j a  va2s  . co m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {/*from  w  w w  .  ja v  a 2s  . co m*/
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:com.lostad.app.base.util.RequestUtil.java

/** 
 * HTTP??????,??? /*w  ww  . j a v a2 s  . c om*/
 * @param actionUrl  
 * @param params ? key???,value? 
 * @param files 
 * @throws Exception 
 */
public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token)
        throws Exception {
    try {
        String BOUNDARY = "---------7d4a6d158c9"; //?  
        String MULTIPART_FORM_DATA = "multipart/form-data";

        URL url = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);//?  
        conn.setDoOutput(true);//?  
        conn.setUseCaches(false);//?Cache  
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        conn.setRequestProperty("token", token);
        //????
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {//?  
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                sb.append(entry.getValue());
                sb.append("\r\n");
            }
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());//????  

        //??  
        for (FormFile file : files) {
            StringBuilder split = new StringBuilder();
            split.append("--");
            split.append(BOUNDARY);
            split.append("\r\n");
            split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\""
                    + file.getFilname() + "\"\r\n");
            split.append("Content-Type: " + file.getContentType() + "\r\n\r\n");
            outStream.write(split.toString().getBytes());
            outStream.write(file.getData(), 0, file.getData().length);
            outStream.write("\r\n".getBytes());
        }
        byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//??           
        outStream.write(end_data);
        outStream.flush();
        int cah = conn.getResponseCode();
        if (cah != 200)
            throw new RuntimeException("url");
        InputStream is = conn.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        outStream.close();
        conn.disconnect();
        return b.toString();
    } catch (Exception e) {

        throw e;
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Http//from  ww  w. j  a v  a  2  s  .c om
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param outputJson    ?
 * @return 
 */
public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

From source file:RemoteDeviceDiscovery.java

public static void postDevice(RemoteDevice d) throws Exception {
    String url = "http://bluetoothdatabase.com/datacollection/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "blucat");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = deviceJson(d);

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);//from   www.  j a v a 2  s .  c o m
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
}

From source file:BihuHttpUtil.java

/**
 * ??HTTPJSON?/* w w  w . jav  a 2  s  .  c o  m*/
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:gribbit.util.RequestBuilder.java

/**
 * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true,
 * returns a byte[] array, otherwise returns the response as a String.
 *///from www  .  ja  va 2s.  co  m
private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse,
        int redirDepth) {
    if (redirDepth > 6) {
        throw new IllegalArgumentException("Too many redirects");
    }
    HttpURLConnection connection = null;
    try {
        // Add the URL query params if this is a GET request
        String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url;
        connection = (HttpURLConnection) new URL(reqURL).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(isGET ? "GET" : "POST");
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                        + "Chrome/43.0.2357.125 Safari/537.36");
        if (!isGET) {
            // Send the body if this is a POST request
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            String params = WebUtils.buildQueryString(keyValuePairs);
            connection.setRequestProperty("Content-Length", Integer.toString(params.length()));
            try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) {
                w.writeBytes(params);
                w.flush();
            }
        }
        if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) {
            // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET.
            return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */
                    true, isBinaryResponse, redirDepth + 1);
        } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) {
            // For 200 OK, return the text of the response
            if (isBinaryResponse) {
                ByteArrayOutputStream output = new ByteArrayOutputStream(32768);
                IOUtils.copy(connection.getInputStream(), output);
                return output.toByteArray();
            } else {
                StringWriter writer = new StringWriter(1024);
                IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
                return writer.toString();
            }
        } else {
            throw new IllegalArgumentException(
                    "Got non-OK HTTP response code: " + connection.getResponseCode());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static HttpURLConnection getConnectionForPrivateUpload(final URL url, final String contentType)
        throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpPut.METHOD_NAME);

    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
    connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PRIVATE);
    connection.setDoOutput(true);
    connection.connect();/*  w  w w  .  jav a2  s. c om*/
    return connection;
}