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

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

Introduction

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

Prototype

public DefaultHttpClient() 

Source Link

Usage

From source file:com.jt.https.test.send.java

public static String PostTo(String content) {
    String responseMessage = null;
    String filePath = "";
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }// w  w  w . j a  v a  2s . c  om
    HttpClient httpclient = new DefaultHttpClient();
    try {
        KeyStore keystore = KeyStore.getInstance("jks");
        KeyStore trustStore = KeyStore.getInstance("jks");

        FileInputStream keystoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks"));
        FileInputStream trustStoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks"));
        //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks"));
        //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks"));
        try {
            keystore.load(keystoreInstream, "123456".toCharArray());
            trustStore.load(trustStoreInstream, "paic1234".toCharArray());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            keystoreInstream.close();
            trustStoreInstream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456",
                trustStore, null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 8107, socketFactory);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpPost post = new HttpPost("https://222.68.184.181:8107");

        StringEntity entity = new StringEntity(content, "text/html", "UTF-8");
        post.setEntity(entity);
        HttpResponse res = httpclient.execute(post);
        HttpEntity resEntity = res.getEntity();
        if (resEntity != null) {
            responseMessage = convertStreamToString(resEntity.getContent());
            System.out.println("???" + content);
            System.out.println("?" + responseMessage);
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return responseMessage;
}

From source file:core.RESTCalls.RESTGet.java

public static InputStream httpGetResponse(String urlStr) {

    InputStream inputStream = null;

    try {/*w  ww .  j a  v  a  2 s . co  m*/

        HttpClient client = new DefaultHttpClient();

        HttpGet get = new HttpGet(urlStr);

        HttpResponse response = client.execute(get);

        inputStream = response.getEntity().getContent();
    }

    catch (Exception ex) {

        ex.printStackTrace();
    }

    return inputStream;
}

From source file:uk.org.todome.Util.java

public static String getFileFromServer(String request) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(request);
    Log.i("Util.getFileFromServer", "Request used: " + request);
    try {/*from   w  ww  . jav  a 2  s.  co  m*/
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("", "Failed to download file");
        }
    } catch (Exception ex) {
        Log.e("Util.getFileFromServer", ex.getClass().toString() + " " + ex.getMessage());
    }

    return builder.toString();
}

From source file:it410.gmu.edu.OrderingServiceClient.java

public static void getCustomersJSON() throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://localhost:8080/BookstoreRestService/generic/getOrdersJSON");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    StringBuilder sb = new StringBuilder();

    while ((line = rd.readLine()) != null) {
        //System.out.println(line);
        sb.append(line);//from  w  ww. j  a  v a2 s.  c  o m
    }
    System.out.println("Customers JSON = " + sb.toString());

    Gson gson = new Gson();
    Customers customers = gson.fromJson(new StringReader(sb.toString()), Customers.class);

    System.out.println(" JSON Customer List size = " + customers.getCustomersJSON().size());
}

From source file:bsb.vote.service.DoVote.java

/**
 * @param VOTE_NUM//from  w ww  .  jav a 2  s  . c o  m
 * @param ITEM_ID
 * @param V_ID
 */
public static void doVote(int VOTE_NUM, String ITEM_ID, String V_ID) {
    // TODO code application logic here
    MainUI.startFlag = false;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //??????????  
    //192.168.1.107?? 808?? UsernamePasswordCredentials??????  
    //        httpclient.getCredentialsProvider().setCredentials(new AuthScope("127.0.0.1", 8888), new UsernamePasswordCredentials("", ""));
    //        HttpHost proxy = new HttpHost("127.0.0.1", 8888);
    //        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    //??
    MainUI.voteNum = 0;
    MainUI.regNum = 0;
    MainUI.validNum = 0;
    int j = 0;
    //        try {
    //            getId(httpclient);
    //            getList(httpclient);
    //        } catch (IOException | JSONException ex) {
    //            Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    //        
    for (int i = 0; i < VOTE_NUM; i++) {
        try {
            MainUI.voteNum++;
            httpclient.getCookieStore().clear();
            Thread.sleep(1000);
            try {
                if (regUser(httpclient)) {
                    MainUI.regNum++;
                } else {
                    continue;
                }
            } catch (IOException | JSONException ex) {
                Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
            }
            Thread.sleep(500);
            try {
                if (vote(httpclient, ITEM_ID, V_ID)) {
                    MainUI.validNum++;
                }
            } catch (IOException ex) {
                Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
            }
            j++;
            if (j == 15) {
                Thread.sleep(60000 * 2);
                j = 0;
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MainUI.startFlag = true;
    //
    httpclient.getConnectionManager().shutdown();
}

From source file:com.firewallid.util.FIConnection.java

public static void sendJson(String host, String json) throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(host);

    StringEntity input = new StringEntity(json);
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from ww  w.  j  ava2 s.  com*/

    HttpResponse response = httpClient.execute(postRequest);
}

From source file:edu.ucsd.ccdb.cil.xml2json.ElasticsearchClient.java

public void xputElastic(String index, String type, String ID, File f) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    String url = "http://localhost:9200/" + index + "/" + type + "/" + ID;
    System.out.println(url);//w  w w.  j av a  2  s  .  c  om
    HttpPut put = new HttpPut(url); //-X PUT
    put.setEntity(new FileEntity(f, "application/json")); //@ - absolute path
    BasicResponseHandler responseHandler = new BasicResponseHandler();

    String o = httpClient.execute(put, responseHandler);
    /* System.err.println("----------"+o+"----------");
     if(o == null || o.trim().length() == 0)
     {
         System.err.println(o);
         System.exit(1);
     } */

}

From source file:com.android.fastlibrary.volley.VolleyHelper.java

public static void init(Context context) {
    if (requestQueue == null) {
        httpClient = new DefaultHttpClient();
        requestQueue = Volley.newRequestQueue(context, new HttpClientStack(httpClient));
    }/*  ww w.ja  va  2s  .  c o m*/
}

From source file:it.agileday.utils.HttpRestUtil.java

public static JSONObject httpGetJsonObject(String uri) {
    try {/* w ww . j a v a2 s.  co m*/
        HttpGet httpGetRequest = new HttpGet(uri);
        httpGetRequest.setHeader("Accept", "application/json");
        httpGetRequest.setHeader("Accept-Encoding", "gzip");

        HttpResponse response = new DefaultHttpClient().execute(httpGetRequest);
        HttpEntity entity = response.getEntity();
        JSONObject ret = null;
        if (entity != null) {
            InputStream stream = entity.getContent();
            try {
                if (HttpRestUtil.isGzipEncoded(response)) {
                    stream = new GZIPInputStream(stream);
                }
                String str = HttpRestUtil.convertStreamToString(stream);
                ret = new JSONObject(str);
            } finally {
                stream.close();
            }
        }
        return ret;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.factpub.ui.gui.network.PostFile.java

public static List<String> uploadToFactpub(File file) throws Exception {
    List<String> status = new ArrayList<String>();
    int i = 0;//  w w  w  .j  ava2s .co  m

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps="
            + AuthMediaWikiIdHTTP.userPassword;

    HttpPost httppost = new HttpPost(postUrl);

    System.out.println(postUrl);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "json");

    // name must be "uploadfile". this is same on the server side.
    mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());

    if (response.getStatusLine().toString().contains("502 Bad Gateway")) {
        status.add("Looks server is down.");
    } else {
        if (resEntity != null) {
            status.add(EntityUtils.toString(resEntity));
            System.out.println(status.get(i));
            i++;
        }

        if (resEntity != null) {
            resEntity.consumeContent();
        }
    }
    httpclient.getConnectionManager().shutdown();

    //String status = "Upload Success!";
    return status;
}