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.orange.oidc.tim.service.HttpOpenidConnect.java

public static boolean logout(String server_url, String tim_access_token) {

    if (isEmpty(server_url)) {
        Logd(TAG, "logout failed : no server url");
        return false;
    }/*from  w w  w  .ja  v  a 2  s . com*/

    // get revoke_logout endpoint
    String revoke_logout_endpoint = getEndpointFromConfigOidc("revoke_logout_endpoint", server_url);
    if (isEmpty(revoke_logout_endpoint)) {
        Logd(TAG, "logout : could not get revoke_logout_endpoint on server : " + server_url);
        return false;
    }

    // set up connection
    HttpURLConnection huc = getHUC(revoke_logout_endpoint);
    huc.setInstanceFollowRedirects(false);

    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setDoOutput(true);
    huc.setChunkedStreamingMode(0);
    // prepare parameters
    List<NameValuePair> nameValuePairs = null;
    if (tim_access_token != null && tim_access_token.length() > 0) {
        nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("tat", tim_access_token));
    }

    try {
        // write parameters to http connection
        if (nameValuePairs != null) {
            OutputStream os = huc.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            // get URL encoded string from list of key value pairs
            String postParam = getQuery(nameValuePairs);
            Logd("Logout", "url: " + revoke_logout_endpoint);
            Logd("Logout", "POST: " + postParam);
            writer.write(postParam);
            writer.flush();
            writer.close();
            os.close();
        }

        // try to connect
        huc.connect();
        // connection status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "Logout response: " + responseCode);
        // if 200 - OK
        if (responseCode == 200) {
            return true;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.jongo.mocks.JongoClient.java

private JongoResponse doRequest(final String url, final String method) {
    JongoResponse response = null;/*from   www  .  j av  a2s .  c om*/
    try {
        HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection();
        con.setRequestMethod(method);
        con.setDoOutput(true);
        con.setRequestProperty("Accept", MediaType.APPLICATION_XML);
        BufferedReader r = null;

        if (con.getResponseCode() != Response.Status.OK.getStatusCode()) {
            r = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        } else {
            r = new BufferedReader(new InputStreamReader(con.getInputStream()));
        }
        StringBuilder rawresponse = new StringBuilder();
        String strLine = null;
        while ((strLine = r.readLine()) != null) {
            rawresponse.append(strLine);
            rawresponse.append("\n");
        }
        try {
            response = XmlXstreamTest.successFromXML(rawresponse.toString());
        } catch (Exception e) {
            response = XmlXstreamTest.errorFromXML(rawresponse.toString());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return response;
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static Map<String, String> sendToServer(String epPostFix, Map<String, String> params, String option,
        Context context) throws IOException {
    String response = null;/*from   ww  w .  jav a 2  s  . c  om*/
    Map<String, String> response_params = new HashMap<String, String>();
    String endpoint = CommonUtilities.SERVER_URL + epPostFix;

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    String ipSaved = mainPref.getString("ip", "");

    if (ipSaved != null && ipSaved != "") {
        endpoint = CommonUtilities.SERVER_PROTOCOL + ipSaved + ":" + CommonUtilities.SERVER_PORT
                + CommonUtilities.SERVER_APP_ENDPOINT + epPostFix;
    }

    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    HttpsURLConnection sConn = null;
    try {

        if (url.getProtocol().toLowerCase().equals("https")) {

            sConn = (HttpsURLConnection) url.openConnection();
            sConn = getTrustedConnection(context, sConn);
            sConn.setHostnameVerifier(WSO2MOBILE_HOST);
            conn = sConn;

        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod(option);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Connection", "close");
        // post the request
        int status = 0;
        Log.v("Check verb", option);
        if (!option.equals("DELETE")) {
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            status = conn.getResponseCode();
            Log.v("Response Status", status + "");
            InputStream inStream = conn.getInputStream();
            response = inputStreamAsString(inStream);
            response_params.put("response", response);
            Log.v("Response Message", response);
            response_params.put("status", String.valueOf(status));
        } else {
            status = Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL);
        }
        if (status != Integer.valueOf(CommonUtilities.REQUEST_SUCCESSFUL)
                && status != Integer.valueOf(CommonUtilities.REGISTERATION_SUCCESSFUL)) {
            throw new IOException("Post failed with error code " + status);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response_params;
}

From source file:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java

/**
 * Upload a file to the given URL//from w  w w.j ava  2  s  .c  o m
 *
 * @param endpointUrl URL to be file upload
 * @param fileName    Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private HttpResponse uploadFile(String endpointUrl, File fileName, Map<String, String> headers)
        throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(endpointUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    //setting headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                connection.setRequestProperty(key, headers.get(key));
            }
        }
        for (String key : headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
    }

    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder responseMsg = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        responseMsg.append(temp);
    }
    HttpResponse response = new HttpResponse(responseMsg.toString(), status);
    return response;
}

From source file:ca.weblite.contacts.webservice.RESTService.java

private boolean sendPush(String[] deviceIds, String message, String type) throws IOException {
    StringBuilder sb = new StringBuilder();
    for (String did : deviceIds) {
        sb.append("&device=").append(did);
    }//from  w  w w .  j  a  va 2  s.  c  o m
    String device = sb.toString();
    HttpURLConnection connection = (HttpURLConnection) new URL("https://push.codenameone.com/push/push")
            .openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    //String device = "&device=6430232162074624&device=6095332624039936";

    String query = "token=" + RESTServiceConfiguration.getPushToken() + device + "&type=" + type + "&auth="
            + RESTServiceConfiguration.getGcmApiKey() + "&certPassword="
            + RESTServiceConfiguration.getIOSPushCertPassword() + "&cert="
            + RESTServiceConfiguration.getIOSPushCertURL() + "&body=" + URLEncoder.encode(message, "UTF-8")
            + "&production=false";

    System.out.println("Query is " + query);
    try (OutputStream output = connection.getOutputStream()) {
        output.write(query.getBytes("UTF-8"));
    }
    //        catch (IOException ex) {
    //            Logger.getLogger(RESTService.class.getName()).log(Level.SEVERE, null, ex);
    //        }

    int responseCode = connection.getResponseCode();
    System.out.println("Push response code " + responseCode);
    switch (responseCode) {
    case 200:
    case 201: {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());
        break;
    }
    default: {

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());

        return false;
    }

    }

    return true;
}

From source file:com.adamrosenfield.wordswithcrosses.net.DerStandardDownloader.java

private HttpURLConnection getHttpPostConnection(String url, String postData)
        throws IOException, MalformedURLException {
    HttpURLConnection conn = getHttpConnection(url);

    conn.setRequestMethod("POST");
    conn.setDoOutput(true);

    OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
    try {// w w  w  .j a va2  s.  c o m
        osw.append(postData);
    } finally {
        osw.close();
    }

    return conn;
}

From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java

/**
 *
 * @param query//  w ww  . java 2  s .c  o m
 * @return
 */
public double executeQuery(String query) {

    double score = 0.0;

    try {
        String url = elasticSearchQueryURI;

        //open connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        //write data to socket
        try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream())) {
            out.write(query);
            out.close();
        }

        String json = "";
        String line = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //get response
        while ((line = in.readLine()) != null) {
            json = json + line + " ";
        }

        //            System.out.println(json);
        //transfor response to JSONObject
        JSONObject jsonObj = new JSONObject(json);
        try {
            //get max_score
            score = jsonObj.getJSONObject("hits").getDouble("max_score");
        } catch (JSONException ex) {
            score = 0.0;
        }

        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException ex) {
        Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex);
    }

    return score;
}

From source file:de.openknowledge.jaxrs.versioning.AddressResourceTest.java

private InputStream send(URL url, String method, String resource) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/json");
    PrintWriter writer = new PrintWriter(connection.getOutputStream());
    for (String line : IOUtils.readLines(AddressV1.class.getResourceAsStream(resource))) {
        writer.write(line);// w  w  w. jav  a2  s .  com
    }
    writer.close();
    return connection.getInputStream();
}

From source file:com.trafficspaces.api.controller.Connector.java

public String sendRequest(String path, String contentType, String method, String data)
        throws IOException, TrafficspacesAPIException {

    URL url = new URL(endPoint.baseURI + path);

    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod(method.toUpperCase());

    String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes());
    httpCon.setRequestProperty("Authorization", basicAuth);

    httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8");
    httpCon.setRequestProperty("Accept", contentType);

    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        httpCon.setRequestProperty("Content-Length", String.valueOf(data.length()));
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);/*from  w w  w  .  j  a v a2  s .c  o  m*/
        out.close();
    } else {
        httpCon.connect();
    }

    char[] responseData = null;
    try {
        responseData = readResponseData(httpCon.getInputStream(), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        // HTTP 404. Ignore and return null
    }
    String responseDataString = null;
    if (responseData != null) {
        int responseCode = httpCon.getResponseCode();
        String redirectURL = null;
        if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_CREATED)
                && (redirectURL = httpCon.getHeaderField("Location")) != null) {
            //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL);
            return sendRequest(redirectURL, contentType);
        }
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new TrafficspacesAPIException(
                    "HTTP Error: " + responseCode + "; Data: " + new String(responseData));
        }
        //System.out.println("Headers: " + httpCon.getHeaderFields());
        //System.out.println("Data: " + new String(responseData));
        responseDataString = new String(responseData);
    }
    return responseDataString;
}

From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java

@Override
protected Payload doInBackground(Payload... params) {
    Payload payload = params[0];/*w  w  w  .j  a va 2s  .  c o m*/

    Course dm = (Course) payload.getData().get(0);
    DownloadProgress dp = new DownloadProgress();
    try {
        HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);

        String url = client.createUrlWithCredentials(dm.getDownloadUrl());

        Log.d(TAG, "Downloading:" + url);

        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        c.setConnectTimeout(
                Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection),
                        ctx.getString(R.string.prefServerTimeoutConnection))));
        c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response),
                ctx.getString(R.string.prefServerTimeoutResponse))));

        int fileLength = c.getContentLength();

        String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip";

        dp.setMessage(localFileName);
        dp.setProgress(0);
        publishProgress(dp);

        Log.d(TAG, "saving to: " + localFileName);

        FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName));
        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;
        int progress = 0;
        while ((len1 = in.read(buffer)) > 0) {
            total += len1;
            progress = (int) (total * 100) / fileLength;
            if (progress > 0) {
                dp.setProgress(progress);
                publishProgress(dp);
            }
            f.write(buffer, 0, len1);
        }
        f.close();

        dp.setProgress(100);
        publishProgress(dp);
        dp.setMessage(ctx.getString(R.string.download_complete));
        publishProgress(dp);
        payload.setResult(true);
    } catch (ClientProtocolException cpe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(cpe);
        } else {
            cpe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (SocketTimeoutException ste) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ste);
        } else {
            ste.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    } catch (IOException ioe) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(ioe);
        } else {
            ioe.printStackTrace();
        }
        payload.setResult(false);
        payload.setResultResponse(ctx.getString(R.string.error_connection));
    }

    return payload;
}