Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:com.fota.Link.sdpApi.java

public static String getCtnInfo(String ncn) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {//from   w ww  .  j a  v a  2  s .co m
        String cpId = PropUtil.getPropValue("sdp3g.id");
        String cpPw = PropUtil.getPropValue("sdp3g.pw");
        String authorization = cpId + ":" + cpPw;
        logData = "\r\n---------- Get Ctn Req Info start ----------\r\n";
        logData += " getCtnRequestInfo - authorization : " + authorization;
        byte[] encoded = Base64.encodeBase64(authorization.getBytes());
        authorization = new String(encoded);

        String contractType = "0";
        String contractNum = ncn.substring(0, 9);
        String customerId = ncn.substring(10, ncn.length() - 1);

        JSONObject reqJObj = new JSONObject();
        reqJObj.put("transactionid", "");
        reqJObj.put("sequenceno", "");
        reqJObj.put("userid", "");
        reqJObj.put("screenid", "");
        reqJObj.put("CONTRACT_NUM", contractNum);
        reqJObj.put("CUSTOMER_ID", customerId);
        reqJObj.put("CONTRACT_TYPE", contractType);

        authorization = "Basic " + authorization;

        String endPointUrl = PropUtil.getPropValue("sdp.oif555.url");

        logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl;
        logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization;
        logData += "\r\n getCtnRequestInfo - Content-type : application/json";
        logData += "\r\n getCtnRequestInfo - RequestMethod : POST";
        logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString();
        logData += "\r\n---------- Get Ctn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Authorization", authorization);
        connection.setRequestProperty("Content-type", "application/json");

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(reqJObj.toJSONString());
        wr.flush();
        wr.close();

        // input
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine = "";
        StringBuffer response = new StringBuffer();

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

        in.close();

        JSONParser jsonParser = new JSONParser();
        JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString());

        //         String respTransactionId = (String) respJsonObject.get("transactionid");
        //         String respSequenceNo = (String) respJsonObject.get("sequenceno");
        //         String respReturnCode = (String) respJsonObject.get("returncode");
        //         String respReturnDescription = (String) respJsonObject.get("returndescription");
        //         String respErrorCode = (String) respJsonObject.get("errorcode");
        //         String respErrorDescription = (String) respJsonObject.get("errordescription");
        String respCtn = (String) respJsonObject.get("ctn");
        //         String respSubStatus = (String) respJsonObject.get("sub_status");
        //         String respSubStatusDate = (String) respJsonObject.get("sub_status_date");

        resultStr = respCtn;

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

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

    return resultStr;
}

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

String remoteCall(String request, String requestPath, String method) {
    boolean acquired = false;
    try {/*from w  ww  . ja v a2 s  .  com*/
        CONCURRENT_REQUEST_MANAGER.acquire();
        acquired = true;
        HttpURLConnection connection = openConnection(requestPath, method);
        OutputStream out = connection.getOutputStream();
        out.write(request.getBytes(ConfigurationManager.UTF_8));
        out.flush();
        out.close();
        return new String(readInputStream(connection.getInputStream()), Charset.forName("UTF-8"));
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("thread interrupted", e);
    } catch (IOException e) {
        throw new IllegalStateException("IOException", e);
    } finally {
        if (acquired) {
            CONCURRENT_REQUEST_MANAGER.release();
        }
    }
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * /*  ww  w.  j  av a2 s  .com*/
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

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

/**
 * ?Http/* w ww . java 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:com.notonthehighstreet.ratel.internal.utility.HttpRequestTest.java

@Test
public void callShouldMakeHTTPRequest() throws Exception {
    final String method = "GET";
    final String parameterName = "name";
    final String parameterValue = "value";
    final Object body = new Object();

    final int expected = 123123;

    final HttpURLConnection connection = mock(HttpURLConnection.class);

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    when(connection.getOutputStream()).thenReturn(outputStream);
    when(connection.getResponseCode()).thenReturn(expected);

    final int actual = subject.call(connection, method, Collections.singletonMap(parameterName, parameterValue),
            body);// ww w  . j  a  va 2  s. c om

    assertEquals(expected, actual);

    verify(mapper).writeValue(same(outputStream), same(body));
    verify(connection).setRequestMethod(eq(method));
    verify(connection).setReadTimeout(anyInt());
    verify(connection).setConnectTimeout(anyInt());
    verify(connection).setDoOutput(eq(true));
    verify(connection).setRequestProperty(eq(parameterName), eq(parameterValue));
}

From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java

/** Write the data to the HTTP connection. */
private void writeBodyData(String data, HttpURLConnection conn) throws IOException {
    if (data != null) {
        try (OutputStream os = conn.getOutputStream()) {
            os.write(data.getBytes());/* ww w . j  a v  a  2  s  .  c o  m*/
            os.flush();
        }
    }
}

From source file:com.screenslicer.common.CommonUtil.java

public static String post(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {//  w ww.j av a  2  s.  c  o m
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(0);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        if (conn.getResponseCode() == 205) {
            return NOT_BUSY;
        }
        if (conn.getResponseCode() == 423) {
            return BUSY;
        }
        return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
    return "";
}

From source file:com.ab.network.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.j a  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;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

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

/**
 * Sends a string via POST to a given url.
 *
 * @param context      the context to use.
 * @param urlStr       the url to which to send to.
 * @param string       the string to send as post body.
 * @param user         the user or <code>null</code>.
 * @param password     the password or <code>null</code>.
 * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message.
 * @return the response.//from w  ww  .j a va 2  s.c o m
 * @throws Exception if something goes wrong.
 */
public static String sendPost(Context context, String urlStr, String string, String user, String password,
        boolean readResponse) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        // Make server believe we are form data...
        wr = new BufferedOutputStream(conn.getOutputStream());
        byte[] bytes = string.getBytes();
        wr.write(bytes);
        wr.flush();

        int responseCode = conn.getResponseCode();
        if (readResponse) {
            StringBuilder returnMessageBuilder = new StringBuilder();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    returnMessageBuilder.append(line + "\n");
                }
                br.close();
            }

            return returnMessageBuilder.toString();
        } else {
            return getMessageForCode(context, responseCode,
                    context.getResources().getString(R.string.post_completed_properly));
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.wudoumi.batter.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case RequestType.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);//from www.j  ava 2s .  co  m
            out.close();
        }
        break;
    case RequestType.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case RequestType.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case RequestType.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case RequestType.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}