Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:org.gatein.sso.saml.plugin.SAML2IdpLoginModule.java

private ResponseContext executeRemoteCall(String authUrl) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method;//from  w ww. j a  va  2  s .  c om

    try {
        method = new HttpGet(authUrl);
        HttpResponse httpResponse = client.execute(method);

        int status = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity = httpResponse.getEntity();
        String response = entity == null ? null : EntityUtils.toString(entity);

        if (log.isTraceEnabled()) {
            log.trace("Received response from REST call: status=" + status + ", response=" + response);
        }

        return new ResponseContext(status, response);
    } catch (Exception e) {
        log.warn("Error when sending request through HTTP client", e);
        return new ResponseContext(1000, e.getMessage());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.mycompany.kerberosbyip.NewMain.java

private void doSendRequest() throws Exception {

    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("request");
    String requestBody = new Scanner(stream, "UTF-8").useDelimiter("\\A").next();

    final DefaultHttpClient client = new DefaultHttpClient(new BasicClientConnectionManager());

    try {//from   w  ww  .  j ava2 s.  c  om
        configureHttpClient(client);
        final HttpEntity entity = createEntity(requestBody);

        final HttpPost post = new HttpPost("/wsman");
        post.setHeader("Content-Type", SOAPConstants.SOAP_1_2_CONTENT_TYPE + "; charset=utf-8");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("SOAPAction", "http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate");
        post.setEntity(entity);

        final HttpResponse response = client.execute(new HttpHost(ipAddress, port, "http"), post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception(String.format("Unexpected HTTP response on %s:  %s (%s)", ipAddress,
                    response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode()));
        }

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:requestToApi.java

public String send(StringEntity Input, String URL) {
    String output2 = "";
    try {/*from w ww  .java2 s.  c om*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(URL);

        StringEntity input = Input;

        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            output2 = output;
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();

        return output2;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return output2;
}

From source file:com.krishna.wiremock.krishna.HttpFetch.java

public String httpPost() {
    //Url = "C:\\Users\\sony\\Documents\\NetBeansProjects\\Wiremock-Krishna\\src\\test\\resources\\__files\\fil.json"; 
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from  w  w w .  j av a2  s .co m*/
        HttpGet getRequest = new HttpGet(HOST + PORT + URL);
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);
        // GsonConverted conv = new GsonConverted();
        //Url = "";
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        StringBuffer out = new StringBuffer();
        String output;
        System.out.println("This is my new Wiremock-krishna sample file \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            out.append(output);
        }

        httpClient.getConnectionManager().shutdown();
        return out.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.betaplay.sdk.http.HttpClient.java

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = sslClient(new DefaultHttpClient());
    HttpParams params = client.getParams();

    // timeout 40 sec
    HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
    HttpConnectionParams.setSoTimeout(params, 40 * 1000);

    HttpResponse httpResponse;/*  w  w  w  .  j a v a2s.c  o m*/

    try {
        httpResponse = client.execute(request);
        mResponseCode = httpResponse.getStatusLine().getStatusCode();
        mMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            mResponse = convertStreamToString(instream);

            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

From source file:com.yaon.NewServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w .ja v  a  2s.c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text");
    PrintWriter out = response.getWriter();
    String ip = request.getParameter("ip");
    String port = request.getParameter("port");
    String uname = request.getParameter("uname");
    String pass = request.getParameter("pass");
    StringWriter sw = new StringWriter();
    if ("null".equals(ip) && "null".equals(port) && "null".equals(uname) && "null".equals(pass)) {

        out.println("Null Argument Passed !!");
    } else {
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://" + ip + ":" + port + "/Yaon/GetInfo");
            postRequest.addHeader(
                    BasicScheme.authenticate(new UsernamePasswordCredentials(uname, pass), "UTF-8", false));
            HttpResponse res = httpClient.execute(postRequest);

            if (res.getStatusLine().getStatusCode() == 401) {
                throw new Exception("Http Authentication Failed !");
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((res.getEntity().getContent())));

            String output;
            System.out.println("Output from Server.... \n");
            while ((output = br.readLine()) != null) {

                System.out.println(output);
                sw.append(output);
                sw.append("\n");
            }
            httpClient.getConnectionManager().shutdown();

        } catch (HttpHostConnectException e) {
            out.println(e.getMessage());
        } catch (Exception e) {
            out.println(e.getMessage());
        }

        out.println(sw.toString());
    }
}

From source file:org.opentraces.metatracker.net.OpenTracesClient.java

public void uploadFile(String fileName) {
    try {/*from  w ww. j a  v  a2s  .  c om*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        File f = new File(fileName);

        HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("myIdentifier", new StringBody("somevalue"));
        entity.addPart("myFile", new FileBody(f));
        httpost.setEntity(entity);

        HttpResponse response;

        response = httpclient.execute(httpost);

        Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());

        if (entity != null) {
            entity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();

    } catch (Throwable ex) {
        Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
    }

}

From source file:dk.moerks.ratebeermobile.io.NetBroker.java

public static String doPost(Context context, DefaultHttpClient httpclient, String url,
        List<NameValuePair> parameters) throws NetworkException {
    if (httpclient == null) {
        httpclient = init();//from ww  w  . j a v a  2  s  .  c om
    }

    HttpPost httppost = new HttpPost(url);
    //httppost.setHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 7.0; Windows 2000)");

    for (Iterator<NameValuePair> iterator = parameters.iterator(); iterator.hasNext();) {
        NameValuePair nameValuePair = iterator.next();
        Log.d(LOGTAG, nameValuePair.getName() + " :: " + nameValuePair.getValue());
    }

    try {
        // Add your data  
        httppost.setEntity(new UrlEncodedFormEntity(parameters));

        // Execute HTTP Post Request
        Log.d(LOGTAG, "Executing Post");
        HttpResponse response = httpclient.execute(httppost);
        Log.d(LOGTAG, "Post Executed");
        Log.d(LOGTAG, "Post Response Code: " + response.getStatusLine().getStatusCode());
        String result = responseString(response);
        Log.d(LOGTAG, "Response String length: " + result.length());
        //Log.d(LOGTAG, result);
        response.getEntity().consumeContent();

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        return result;
    } catch (ClientProtocolException e) {
        throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e);
    } catch (IOException e) {
        throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e);
    } catch (Exception e) {
        throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:cloudMe.CloudMeAPI.java

private synchronized String callServerStringResponse() {
    String soapAction = "login";
    String body = "";
    DefaultHttpClient httpClient = getConnection();
    byte[] b = null;
    HttpPost httpPost = new HttpPost("http://" + host + "/v1/");
    httpPost.setHeader("soapaction", soapAction);
    httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
    final StringBuffer soap = new StringBuffer();
    soap.append(SOAP_HEADER);/*from w  ww  . jav  a  2 s. c  om*/
    soap.append("<" + soapAction + ">");
    soap.append(body);
    soap.append("</" + soapAction + ">");
    soap.append(SOAP_FOOTER);
    try {
        HttpEntity entity = new StringEntity(soap.toString());
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        // Call to getResponse needs to be done before httpClient is shut down
        // otherwise the response disappears and null is returned
        String stringResponse = getResponse(response);
        httpClient.getConnectionManager().shutdown();
        return stringResponse;
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    httpClient.getConnectionManager().shutdown();
    return null;
}

From source file:eu.juniper.MonitoringLib.java

/**
 * @param metricName Name of the metric to be sent
 * @param metricValue Value of the metric to be sent
 * @param communicationID communication ID
 * @param connectionName connection name
 * @return Response of the REST POST method, represented as String
 * @throws ParseException/* ww w  . j a  v a  2 s  . c om*/
 */
public String sendMetricValue(String metricName, String metricValue, String communicationID,
        String connectionName) throws ParseException {
    String responseString = "";
    String resource = monitoringServiceURL + appId;
    long milis = System.currentTimeMillis();
    long seconds = System.currentTimeMillis() / 1000;
    String curTime = "" + seconds + "." + (milis - seconds * 1000) * 10000;
    String requestString = "{\"Timestamp\": " + curTime
            + ", \"hostname\": \"testhost\", \"type\": \"testype\", \"" + metricName + "\": " + metricValue
            + ", \"" + "communicationID" + "\": " + communicationID + ", \"" + "connectionName" + "\": \""
            + connectionName + "\" } ";

    System.out.println("requestString = " + requestString);
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(resource);

        System.out.println("executing POST request:\n" + httpPost.getRequestLine());

        httpPost.addHeader("content-type", "application/json");
        httpPost.addHeader("Accept", "application/json");
        StringEntity params = new StringEntity(requestString);
        httpPost.setEntity(params);

        HttpResponse response;
        response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        responseString = EntityUtils.toString(responseEntity);

        httpclient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return responseString;
}