Java 类org.apache.http.impl.client.DefaultHttpClient 实例源码

项目:WeiXinPayDemo    文件:Util.java   
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

       SchemeRegistry registry = new SchemeRegistry(); 
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
       registry.register(new Scheme("https", sf, 443)); 

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
项目:sjk    文件:CatalogConvertorControllerTest.java   
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:letv    文件:PoolingClientConnectionManager.java   
public static HttpClient get() {
    HttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, 3000);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(30));
    ConnManagerParams.setMaxTotalConnections(httpParams, 30);
    HttpClientParams.setRedirecting(httpParams, true);
    HttpProtocolParams.setUseExpectContinue(httpParams, true);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
    HttpConnectionParams.setSoTimeout(httpParams, 2000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, sf, 443));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
}
项目:developNote    文件:HttpUtil.java   
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

       HttpParams params = new BasicHttpParams();
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

       SchemeRegistry registry = new SchemeRegistry(); 
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
       registry.register(new Scheme("https", sf, 443)); 

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) {
       return new DefaultHttpClient(); 
   } 
}
项目:CCDownload    文件:Subtitle.java   
public void initSubtitleResource(final String url) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();
                client.getParams().setParameter(
                        CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
                HttpGet httpGet = new HttpGet(url);
                HttpResponse response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String results = EntityUtils.toString(entity, "utf-8");
                parseSubtitleStr(results);
            } catch (Exception e) {
                Log.e("CCVideoViewDemo", "" + e.getMessage());
            }
        }
    }).start();
}
项目:Charrizard    文件:MyAnimeListQuery.java   
public MyAnimeListQuery(Charrizard charrizard) {
    status = MyAnimeListStatus.UNKNOWN_ERROR;
    errorDescription = "Unknown error.";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://myanimelist.net/api/account/verify_credentials.xml");
        httpGet.addHeader(BasicScheme.authenticate(
                new UsernamePasswordCredentials(charrizard.getSettings().getMyAnimeList().getUsername(), charrizard.getSettings().getMyAnimeList().getUsername()),
                "UTF-8", false));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            status = MyAnimeListStatus.AUTH_ERROR;
            errorDescription = "Authorization Error: " + httpResponse.getStatusLine().getReasonPhrase();
            return;
        }
    } catch (IOException e) {
        status = MyAnimeListStatus.REQUEST_ERROR;
        errorDescription = "Can't connect to MyAnimeList: " + e.getMessage();
        e.printStackTrace();
    }
}
项目:onekey-proxy-android    文件:ProxyConfig.java   
private String[] downloadConfig(String url) throws Exception {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet requestGet = new HttpGet(url);

        requestGet.addHeader("X-Android-MODEL", Build.MODEL);
        requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT));
        requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE);
        requestGet.addHeader("X-App-Version", AppVersion);
        requestGet.addHeader("X-App-Install-ID", AppInstallID);
        requestGet.setHeader("User-Agent", System.getProperty("http.agent"));
        HttpResponse response = client.execute(requestGet);

        String configString = EntityUtils.toString(response.getEntity(), "UTF-8");
        String[] lines = configString.split("\\n");
        return lines;
    } catch (Exception e) {
        throw new Exception(String.format("Download config file from %s failed.", url));
    }
}
项目:android-project-gallery    文件:SyncHttpClient.java   
@Override
  protected RequestHandle sendRequest(DefaultHttpClient client,
                                      HttpContext httpContext, HttpUriRequest uriRequest,
                                      String contentType, ResponseHandlerInterface responseHandler,
                                      Context context) {
      if (contentType != null) {
          uriRequest.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, contentType);
      }

      responseHandler.setUseSynchronousMode(true);

/*
       * will execute the request directly
*/
      newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run();

      // Return a Request Handle that cannot be used to cancel the request
      // because it is already complete by the time this returns
      return new RequestHandle(null);
  }
项目:boohee_v5.6    文件:LEYUApplication.java   
private String GetDate(String url) {
    String resultString = "";
    try {
        return EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet(wwwhost +
                url)).getEntity());
    } catch (Exception e) {
        this._callback.onFailed(e.getMessage());
        return resultString;
    }
}
项目:rongyunDemo    文件:AsyncHttpClient.java   
/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 */
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}
项目:order-by-android    文件:VerificaAluno.java   
@Override
protected Aluno doInBackground(String... rm) {

    //Instancia um cliente http, que fará a requisição do json
    DefaultHttpClient lHttpClient = new DefaultHttpClient();
    //Define um HttpGet, que contém a url
    HttpGet lHttpGet = new HttpGet(url.replace("$rm",rm[0]));
    try {
        //Executa e obtem a resposta da página da API
        HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
        //Lê o resultado
        BufferedReader reader = new BufferedReader(new InputStreamReader(lHttpResponse.getEntity().getContent(), "UTF-8"));

        return analisar(reader.readLine());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:order-by-android    文件:DownloadNotas.java   
@Override
protected List<String> doInBackground(String... url) {
    List<String> jsons = new ArrayList<String>();
    //Laço de repetição que percorre os quatro bimestres
    for(int i=0;i<4;i++) {
        //Instancia um cliente http, que fará a requisição do json
        DefaultHttpClient lHttpClient = new DefaultHttpClient();
        //Define um HttpGet, que contém a url
        HttpGet lHttpGet = new HttpGet(url[0].replace("$rm", mAluno).replace("$bim",String.valueOf(i+1)));
        try {
            //Executa e obtem a resposta da página da API
            HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
            //Lê o resultado
            BufferedReader reader = new BufferedReader(new InputStreamReader(lHttpResponse.getEntity().getContent(), "UTF-8"));

            jsons.add(reader.readLine());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return jsons;
}
项目:order-by-android    文件:DownloadHorario.java   
@Override
protected List<String> doInBackground(String... url) {
    List<String> jsons = new ArrayList<String>();
    //Instancia um cliente http, que fará a requisição do json
    DefaultHttpClient lHttpClient = new DefaultHttpClient();
    //Define um HttpGet, que contém a url
    HttpGet lHttpGet = new HttpGet(url[0].replace("$turma", String.valueOf(mTurma)));
    try {
        //Executa e obtem a resposta da página da API
        HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
        //Lê o resultado
        BufferedReader reader = new BufferedReader(new InputStreamReader(lHttpResponse.getEntity().getContent(), "UTF-8"));

        jsons.add(reader.readLine());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return jsons;
}
项目:order-by-android    文件:DownloadFaltas.java   
@Override
protected List<String> doInBackground(String... url) {
    List<String> jsons = new ArrayList<String>();
    //Laço de repetição que percorre os doze mezes
    for(int i=0;i<12;i++) {
        //Instancia um cliente http, que fará a requisição do json
        DefaultHttpClient lHttpClient = new DefaultHttpClient();
        //Define um HttpGet, que contém a url
        HttpGet lHttpGet = new HttpGet(url[0].replace("$rm", mAluno).replace("$mes",String.valueOf(i+1)));
        try {
            //Executa e obtem a resposta da página da API
            HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
            //Lê o resultado
            BufferedReader reader = new BufferedReader(new InputStreamReader(lHttpResponse.getEntity().getContent(), "UTF-8"));

            jsons.add(reader.readLine());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return jsons;
}
项目:sjk    文件:CatalogConvertorControllerTest.java   
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:appinventor-extensions    文件:WebServiceUtil.java   
/**
 * Returns the one <code>WebServiceUtil</code> instance
 * @return the one <code>WebServiceUtil</code> instance
 */
public static WebServiceUtil getInstance() {
  // This needs to be here instead of in the constructor because
  // it uses classes that are in the AndroidSDK and thus would
  // cause Stub! errors when running the component descriptor.
  synchronized(httpClientSynchronizer) {
    if (httpClient == null) {
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
      BasicHttpParams params = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
      HttpConnectionParams.setSoTimeout(params, 20 * 1000);
      ConnManagerParams.setMaxTotalConnections(params, 20);
      ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params,
          schemeRegistry);
      WebServiceUtil.httpClient = new DefaultHttpClient(manager, params);
    }
  }
  return INSTANCE;
}
项目:sjk    文件:ControllerTest.java   
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);

    String url = "http://localhost:8080/sjk-market/market/brokenLink.d";
    url = "http://app-t.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", encodeBase64);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
项目:sealtalk-android-master    文件:AsyncHttpClient.java   
/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 */
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}
项目:freemoz    文件:HttpRequest.java   
public String executePost(List<NameValuePair> urlParameters) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(this.url);

    post.setHeader("User-Agent", USER_AGENT);
    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);

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

    StringBuffer result = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    return result.toString();
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException
{
    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(
            new AuthScope(host, 8002),
            new UsernamePasswordCredentials("admin", "admin"));
    String  body = "{\"authentication\": \""+level+"\"}";

    HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default");
    put.addHeader("Content-type", "application/json");
    put.setEntity(new StringEntity(body));

    HttpResponse response2 = client.execute(put);
    HttpEntity respEntity = response2.getEntity();
    if(respEntity != null){
        String content =  EntityUtils.toString(respEntity);
        System.out.println(content);
    }
}
项目:WeChatLuckyMoney    文件:UpdateTask.java   
@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 200) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else {
            // Close the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (Exception e) {
        return null;
    }
    return responseString;
}
项目:Higher-Cloud-Computing-Project    文件:ServerUtil.java   
public static String check_email_exist(String email_addr) throws Exception {
    HttpClient client = new DefaultHttpClient();
    String params = "?email_addr=" + email_addr;
    HttpGet get = new HttpGet(url + "/check_email_exist" + params);
    HttpResponse response = client.execute(get);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = null;
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity);
        }
        JSONObject jsonObject = new JSONObject(result);
        int email_exists = jsonObject.getInt("email_exists");
        if (email_exists == 1) {
            return "SUCCESS";
        } else
            return "FAIL";
    } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        return "401 SC_UNAUTHORIZED";
    }
    return "UNKNOWN ERROR";
}
项目:Dendroid-HTTP-RAT    文件:Dialog.java   
public InputStream getInputStreamFromUrl(String urlBase, String urlData) throws UnsupportedEncodingException {

//      Log.d("com.connect", urlBase);
        Log.d("com.connect", urlData);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
        String currentDateandTime = "[" + sdf.format(new Date()) + "] - ";
        currentDateandTime = URLEncoder.encode (currentDateandTime, "UTF-8");

        urlData = URLEncoder.encode (urlData, "UTF-8");

        if(isNetworkAvailable())
        {
          InputStream content = null;
          try 
          {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(new HttpGet(urlBase + currentDateandTime+ urlData));
            content = response.getEntity().getContent();
            httpclient.getConnectionManager().shutdown();
          } catch (Exception e) {
          }
            return content;
        }
        return null;
    }
项目:Hackathon_2017    文件:MainActivity.java   
@Override
protected List<Pregunta> doInBackground(Void... voids) {
    try{
        HttpGet get = new HttpGet("http://192.168.43.167/goc/getQuestions.php");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        String respuesta = EntityUtils.toString(entity);
        String preguntas[] = respuesta.split("\\r\\n|\\n|\\r");
        List<Pregunta> preguntasLista = new ArrayList<>();
        for (String p:preguntas)
            preguntasLista.add(new Pregunta(p.split(";")));
        return preguntasLista;
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}
项目:Zmap_test    文件:RegisterByUsername.java   
private void sendRequestWithHttpClient(){
    final String username_text = username.getText().toString().trim();
    final String password_text = password.getText().toString().trim();
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpCient = new DefaultHttpClient();  //创建HttpClient对象
            HttpGet httpGet = new HttpGet(url+"/?action=register&username="+username_text+"&password="+password_text);
            try {
                HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象
                if((httpResponse.getEntity())!=null){
                    HttpEntity entity =httpResponse.getEntity();
                    String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串

                    Message message = new Message();//在子线程中将Message对象发出去
                    message.what = SHOW_RESPONSE;
                    message.obj =response;
                    handler.sendMessage(message);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}
项目:Mobike    文件:MySSLSocketFactory.java   
/**
 * Gets getUrl DefaultHttpClient which trusts getUrl set of certificates specified by the KeyStore
 *
 * @param keyStore custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {

    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
项目:Zmap_test    文件:SearchPageActivity.java   
/**
 * 将搜索内容发送远端存储
 * @param text:搜索内容
 */
public void putSearchRecordToOrigin(final String text){
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpCient = new DefaultHttpClient();  //创建HttpClient对象
            HttpGet httpGet = new HttpGet(url+"/history.php?action=setHistory" +
                    "&id="+current_user.getUser_id()
                    +"&username="+current_user.getUsername()
                    +"&searchHistory="+text);
            try {
                HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象
                if((httpResponse.getEntity())!=null){
                    HttpEntity entity =httpResponse.getEntity();
                    String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串
                    //TODO ido 处理增加搜索记录的返回结果,规范化验证逻辑
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}
项目:ss-android    文件:ProxyConfig.java   
private String[] downloadConfig(String url) throws Exception {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet requestGet = new HttpGet(url);

        requestGet.addHeader("X-Android-MODEL", Build.MODEL);
        requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT));
        requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE);
        requestGet.addHeader("X-App-Version", AppVersion);
        requestGet.addHeader("X-App-Install-ID", AppInstallID);
        requestGet.setHeader("User-Agent", System.getProperty("http.agent"));
        HttpResponse response = client.execute(requestGet);

        String configString = EntityUtils.toString(response.getEntity(), "UTF-8");
        String[] lines = configString.split("\\n");
        return lines;
    } catch (Exception e) {
        throw new Exception(String.format("Download config file from %s failed.", url));
    }
}
项目:RoadLab-Pro    文件:HockeySender.java   
@Override
public void send(CrashReportData report) throws ReportSenderException {
  String log = createCrashLog(report);
  String url = BASE_URL + ACRA.getConfig().formKey() + CRASHES_PATH;

  try {
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
    parameters.add(new BasicNameValuePair("raw", log));
    parameters.add(new BasicNameValuePair("userID", report.get(ReportField.INSTALLATION_ID)));
    parameters.add(new BasicNameValuePair("contact", report.get(ReportField.USER_EMAIL)));
    parameters.add(new BasicNameValuePair("description", report.get(ReportField.USER_COMMENT)));

    httpPost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));

    httpClient.execute(httpPost);   
  }
  catch (Exception e) {
    e.printStackTrace();
  } 
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void deleteRESTUser(String usrName){
    try{
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/users/"+usrName);

        HttpResponse response = client.execute(delete);
        if(response.getStatusLine().getStatusCode()== 202){
            Thread.sleep(3500);
        }
    }catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }

}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void deleteRESTServerWithDB(String restServerName)    {
    try{
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpDelete delete = new HttpDelete("http://"+host+":8002/v1/rest-apis/"+restServerName+"?include=content&include=modules");

        HttpResponse response = client.execute(delete);
        if(response.getStatusLine().getStatusCode()== 202){
            Thread.sleep(9500);
        }
    }catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException
{
    try {           
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));

            HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response = client.execute(put);
            HttpEntity respEntity = response.getEntity();
            if(respEntity != null){
                String content =  EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        }catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}
项目:sjk    文件:TestTagAppController.java   
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-appsvr/app/api/cdn/tagapp/tagtopic/0/9.json";
    URIBuilder urlb = new URIBuilder(url);
    // 参数
    urlb.setParameter("tabId", "0");
    urlb.setParameter("tagId", "9");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(urlb.build());
    HttpResponse response = httpClient.execute(httpGet);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:aliyun-cupid-sdk    文件:WebProxyCall.java   
public void callWebProxy(String url) {
    String resultCode = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            resultCode = ResponseCode.CALLRESPONSEERROR;
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                if (responseString.contains("Spark Jobs") && responseString.contains("Stages")
                        && responseString.contains("Storage") && responseString.contains("Environment")
                        && responseString.contains("Executors")) {
                    resultCode = ResponseCode.CALLSUCCESS;
                }
            }
        } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            resultCode = ResponseCode.CALLFORBIDDEN;
        } else {
            resultCode = ResponseCode.OTHER_RESPONSE + String.valueOf(statusCode);
        }
    } catch (Exception e) {
        LOG.warn("WebProxyCall exception " + e.getMessage());
        resultCode = ResponseCode.CALLEXCEPTION;
    } finally {
        httpclient.close();
    }
    LOG.info("WebProxyCall result " + resultCode);
    if (!resultCode.equals(ResponseCode.CALLSUCCESS)) {
        System.exit(1);
    }
}
项目:aos-MediaLib    文件:NetworkResourceLoader.java   
/**
 * Create a thread-safe client. This client does not do redirecting, to allow us to capture
 * correct "error" codes.
 *
 * @return HttpClient
 */
public final DefaultHttpClient createHttpClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
    HttpProtocolParams.setUseExpectContinue(params, true);  
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 30 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 10*1000);
    HttpConnectionParams.setSoTimeout(params, 20*1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    ConnManagerParams.setTimeout(params, 5 * 1000);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(50));
    ConnManagerParams.setMaxTotalConnections(params, 200);

    // Sets up the http part of the service.
    final SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    final SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));  
    final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params,
            supportedSchemes);

    DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);

    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    return httpClient;
}
项目:Dendroid-HTTP-RAT    文件:VideoView.java   
public InputStream getInputStreamFromUrl(String urlBase, String urlData) throws UnsupportedEncodingException {

//      Log.d("com.connect", urlBase);
//      Log.d("com.connect", urlData);

        String urlDataFormatted=urlData;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
        String currentDateandTime = "[" + sdf.format(new Date()) + "] - ";
        currentDateandTime = URLEncoder.encode (currentDateandTime, "UTF-8");

        if(urlData.length()>1)
        {
        Log.d("com.connect", urlBase + urlData);

        urlData = currentDateandTime + URLEncoder.encode (urlData, "UTF-8");
        urlDataFormatted = urlData.replaceAll("\\.", "~period");

        Log.d("com.connect", urlBase + urlDataFormatted);
        }

          InputStream content = null;
        if(isNetworkAvailable())
        {
          try 
          {
            Log.i("com.connect", "network push POST");
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(new HttpGet(urlBase + urlDataFormatted));
            content = response.getEntity().getContent();
            httpclient.getConnectionManager().shutdown();
          } catch (Exception e) {
              Log.e("com.connect", "exception", e);
          }
            return content;
        }
        return null;
    }
项目:Android_Code_Arbiter    文件:WeakTLSProtocol.java   
public static void main(String[] args) {
    HttpClient client1 = new DefaultHttpClient(); // BAD

    HttpClient client2 = new SystemDefaultHttpClient(); // OK

    try {
      SSLContext context1 = SSLContext.getInstance("SSL"); // BAD

      SSLContext context2 = SSLContext.getInstance("TLS"); // OK
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
}
项目:boohee_v5.6    文件:MySSLSocketFactory.java   
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme(b.a, sf, WebSocket.DEFAULT_WSS_PORT));
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
项目:instagram4j    文件:Instagram4j.java   
/**
 * Setup some variables
 */
public void setup() {
    log.info("Setup...");

    if (StringUtils.isEmpty(this.username)) {
        throw new IllegalArgumentException("Username is mandatory.");
    }

    if (StringUtils.isEmpty(this.password)) {
        throw new IllegalArgumentException("Password is mandatory.");
    }

    this.deviceId = InstagramHashUtil.generateDeviceId(this.username, this.password);

    if (StringUtils.isEmpty(this.uuid)) {
        this.uuid = InstagramGenericUtil.generateUuid(true);
    }

    if (this.cookieStore == null) {
        this.cookieStore = new BasicCookieStore();
    }

    log.info("Device ID is: " + this.deviceId + ", random id: " + this.uuid);

    this.client = new DefaultHttpClient();
    this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    this.client.setCookieStore(this.cookieStore);

}
项目:aos-MediaLib    文件:XMLRPCClient.java   
/**
     * Sets basic authentication on web request using plain credentials
     * @param username The plain text username
     * @param password The plain text password
     */
    public void setBasicAuthentication(String username, String password) {
        ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(
                new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(),
AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }