Exemplo n.º 1
0
  /**
   * Send get to URL.
   *
   * @param url
   * @return
   */
  public static String sendGet(String url) {
    HttpClient httpClient = new DefaultHttpClient();

    String content = null;
    try {
      if (url.indexOf("https") != -1) {
        httpClient = wrapClient(httpClient);
      }
      HttpGet httpGet = new HttpGet(url);
      // 请求超时
      httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      // 读取超时
      httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);

      httpClient.getParams().setParameter(AllClientPNames.STRICT_TRANSFER_ENCODING, "GBK");

      content = httpClient.execute(httpGet, new BasicResponseHandler());
    } catch (Exception e) {
      log.error("Get url faild, url: " + url, e);
      content = null;
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    return content;
  }
Exemplo n.º 2
0
  /**
   * Explicitly construct a TwilioClient with the given API credentials and endpoint.
   *
   * @param username Username for authentication. For most cases, it is the 34 character Account
   *     identifier (starting with 'AC'). This can be found on your Twilio dashboard page.
   * @param password Password for authentication. For most cases, it is the 32 character AuthToken.
   *     This can be found on your Twilio dashboard page.
   * @param endpoint the url of API endpoint you wish to use. (e.g. - 'https://api.twilio.com')
   */
  public TwilioClient(final String username, final String password, final String endpoint) {
    if (username == null) {
      throw new IllegalArgumentException(
          "username is required. Please provide username or signing key.");
    }
    if (password == null) {
      throw new IllegalArgumentException(
          "password is required. Please provide authToken or signing key secret.");
    }

    this.username = username;
    this.accountSid = username;
    this.password = password;

    if ((endpoint != null) && (!endpoint.equals(""))) {
      this.endpoint = endpoint;
    }

    // Grab the proper connection manager, based on runtime environment
    ClientConnectionManager mgr;
    try {
      Class.forName("com.google.appengine.api.urlfetch.HTTPRequest");
      mgr = new AppEngineClientConnectionManager();
    } catch (final ClassNotFoundException e) {
      // Not GAE
      mgr = new PoolingClientConnectionManager();
      ((PoolingClientConnectionManager) mgr).setDefaultMaxPerRoute(10);
    }

    setHttpClient(new DefaultHttpClient(mgr));
    httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpclient.getParams().setParameter("http.socket.timeout", new Integer(READ_TIMEOUT));
    httpclient.getParams().setParameter("http.connection.timeout", new Integer(CONNECTION_TIMEOUT));
    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
  }
Exemplo n.º 3
0
  public static String sendGet(String url, String encoding, String ip) {
    HttpClient httpClient = new DefaultHttpClient();

    String content = null;
    try {
      if (url.indexOf("https") != -1) {
        httpClient = wrapClient(httpClient);
      }
      HttpGet httpGet = new HttpGet(url);
      if (ip != null) {
        httpGet.setHeader("X-Forwarded-For", ip);
      }
      // 请求超时
      httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      // 读取超时
      httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
      httpClient.getParams().setParameter(AllClientPNames.STRICT_TRANSFER_ENCODING, encoding);
      HttpResponse response = httpClient.execute(httpGet);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        // 使用EntityUtils的toString方法,传递默认编码,在EntityUtils中的默认编码是ISO-8859-1
        content = EntityUtils.toString(entity, encoding);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("Get url faild, url: " + url, e);
      content = null;
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    return content;
  }
Exemplo n.º 4
0
  public void uploadFile(String url, File file, RemoteUploaderResponseListener handler)
      throws ParseException, ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();

    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(10000));
    httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    HttpPost request = new HttpPost(url);

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    entity.addPart(
        "Filename", new StringBody(file.getName(), "text/plain", Charset.forName("UTF-8")));
    entity.addPart("Filedata", new FileBody((file), "application/octet-stream"));
    entity.addPart(
        "Upload", new StringBody("Submit Query", "text/plain", Charset.forName("UTF-8")));
    request.setEntity(entity);

    String response = EntityUtils.toString(httpclient.execute(request).getEntity(), "UTF-8");

    handler.uploaded(file.getName(), file.length(), response);

    httpclient.getConnectionManager().shutdown();
  }
  // 每次都返回新的HttpClient实例
  public static HttpClient getNewInstance(Context mContext) {
    HttpClient newInstance;

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

    // 自定义三个timeout参数

    /*
     * 1.set a timeout for the connection manager,it defines how long we
     * should wait to get a connection out of the connection pool managed by
     * the connection manager
     */
    ConnManagerParams.setTimeout(params, 5000);

    /*
     * 2.The second timeout value defines how long we should wait to make a
     * connection over the network to the server on the other end
     */
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);

    /*
     * 3.we set a socket timeout value to 4 seconds to define how long we
     * should wait to get data back for our request.
     */
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);

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

    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    newInstance = new DefaultHttpClient(conMgr, params);

    switch (checkNetworkType(mContext)) {
      case TYPE_CT_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.200访问www");
        }
        break;
      case TYPE_CM_CU_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.172访问www");
        }
        break;
    }
    return newInstance;
  }
Exemplo n.º 6
0
  private void saveCoverArt(String path, String url) throws Exception {
    InputStream input = null;
    HttpClient client = new DefaultHttpClient();

    try {
      HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds
      HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds
      HttpGet method = new HttpGet(url);

      HttpResponse response = client.execute(method);
      input = response.getEntity().getContent();

      // Attempt to resolve proper suffix.
      String suffix = "jpg";
      if (url.toLowerCase().endsWith(".gif")) {
        suffix = "gif";
      } else if (url.toLowerCase().endsWith(".png")) {
        suffix = "png";
      }

      // Check permissions.
      File newCoverFile = new File(path, "cover." + suffix);
      if (!securityService.isWriteAllowed(newCoverFile)) {
        throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath()));
      }

      // If file exists, create a backup.
      backup(newCoverFile, new File(path, "cover.backup." + suffix));

      // Write file.
      IOUtils.copy(input, new FileOutputStream(newCoverFile));

      MediaFile mediaFile = mediaFileService.getMediaFile(path);

      // Rename existing cover file if new cover file is not the preferred.
      try {
        File coverFile = mediaFileService.getCoverArt(mediaFile);
        if (coverFile != null) {
          if (!newCoverFile.equals(coverFile)) {
            coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old"));
            LOG.info("Renamed old image file " + coverFile);
          }
        }
      } catch (Exception x) {
        LOG.warn("Failed to rename existing cover file.", x);
      }

      mediaFileService.refreshMediaFile(mediaFile);

    } finally {
      IOUtils.closeQuietly(input);
      client.getConnectionManager().shutdown();
    }
  }
Exemplo n.º 7
0
  private static HttpClient getHttpClient() {

    HttpParams httpParameters = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
    HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
    mHttpClient = new DefaultHttpClient(httpParameters);
    mHttpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    mHttpClient.getParams().setParameter("http.socket.timeout", new Integer(2000));
    mHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
    httpParameters.setBooleanParameter("http.protocol.expect-continue", false);

    return mHttpClient;
  }
  @SuppressWarnings("deprecation")
  @Test
  public void assertLegacyCustomConfig() {
    HttpClient httpClient = new DefaultHttpClient(); // Does not support RequestConfig
    HttpComponentsClientHttpRequestFactory hrf =
        new HttpComponentsClientHttpRequestFactory(httpClient);
    hrf.setConnectTimeout(1234);
    assertEquals(
        1234, httpClient.getParams().getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0));

    hrf.setReadTimeout(4567);
    assertEquals(4567, httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
  }
 private static void updateClientProxy(HttpClient paramHttpClient, Session paramSession)
 {
   paramSession = paramSession.getProxyInfo();
   if ((paramSession != null) && (host != null) && (!host.equals("")))
   {
     if (port < 0) {}
     for (paramSession = new HttpHost(host);; paramSession = new HttpHost(host, port))
     {
       paramHttpClient.getParams().setParameter("http.route.default-proxy", paramSession);
       return;
     }
   }
   paramHttpClient.getParams().removeParameter("http.route.default-proxy");
 }
Exemplo n.º 10
0
  private ArrayList<BaseChannel> getChannelCodeData(ArrayList<BaseChannel> otherChannels) {
    ArrayList<BaseChannel> otherHuanChannelList = new ArrayList<BaseChannel>();
    String url = "http://www.epg.huan.tv/json2";
    String errorCode = null;
    String name = creatPostParam(getPostNames(otherChannels)); // ServiceNames
    if (name == null) {
      return null;
    }
    HttpPost request = new HttpPost(url);
    HttpClient client = new DefaultHttpClient();
    // 请求超时
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    // 读取超时
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("jsonstr", name));
    HttpResponse response;
    try {
      request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
      response = client.execute(request);
      Log.i(
          TAG,
          "LocalChannelUtil>>getChannelCodeData>>response code="
              + response.getStatusLine().getStatusCode());
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Log.i(TAG, "LocalChannelUtil>>getChannelCodeData>>start post data from huan");
        HttpEntity entity = response.getEntity();
        Log.i(TAG, "LocalChannelUtil>>getChannelCodeData>>post data done");
        String in = EntityUtils.toString(entity, "UTF-8");
        Log.i(TAG, "LocalChannelUtil>>getChannelCodeData>>in1=" + in);
        JSONObject object = new JSONObject(in);
        otherHuanChannelList = getResultData(object);
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    Log.d(
        TAG,
        "LocalChannelUtil>>getChannelCodeData>>otherHuanChannelList.size()="
            + otherHuanChannelList.size());
    return otherHuanChannelList;
  }
Exemplo n.º 11
0
  private Response getResponseFromHttpClient(Request request) {
    Response response = new Response();
    BufferedReader reader = null;

    int cTimeout = mPrefs.getConnectionTimeout();
    int rTimeout = mPrefs.getReadTimeout();
    String userAgent = mPrefs.getUserAgent();

    try {
      HttpParams params = getHttpParams();
      ClientConnectionManager ccm = getClientConnectionManager(params);
      HttpClient client = new DefaultHttpClient(ccm, params);

      HttpGet get = new HttpGet(request.getUrl());
      HttpConnectionParams.setConnectionTimeout(client.getParams(), cTimeout * 1000);
      HttpConnectionParams.setSoTimeout(client.getParams(), rTimeout * 1000);
      if (userAgent != null && userAgent.length() != 0) {
        get.setHeader("User-Agent", userAgent);
      }

      CodeTimer timer = new CodeTimer();
      HttpResponse res = client.execute(get);

      StatusLine sl = res.getStatusLine();
      int responseCode = sl.getStatusCode();
      response.setResponseCode(responseCode);

      response.setAlive(true);

      InputStream is = res.getEntity().getContent();
      String body = readResponseBody(is);
      response.setResponseTime(timer.getElapsed());
      response.setContent(body.toString());

      response.setHeaderFields(res.getAllHeaders());
    } catch (Throwable t) {
      response.setThrowable(t);
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException ioe) {
      }
    }

    return response;
  }
Exemplo n.º 12
0
 /**
  * This is the parameterized constructor to initialize various fields.
  *
  * @param as Accessor
  */
 public RestAdapter(Accessor as) {
   this.accessor = as;
   DaoConfig config = accessor.getDaoConfig();
   httpClient = config.getHttpClient();
   if (httpClient == null) {
     httpClient = HttpClientFactory.create(DcContext.getPlatform(), config.getConnectionTimeout());
   }
   String proxyHost = config.getProxyHostname();
   int proxyPort = config.getProxyPort();
   if (proxyHost != null) {
     HttpHost proxy = new HttpHost(proxyHost, proxyPort);
     httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
     // ID/Passが共にnullでなければ認証Proxyをセット
     String proxyUsername = config.getProxyUsername();
     String proxyPassword = config.getProxyPassword();
     if (httpClient instanceof AbstractHttpClient
         && proxyUsername != null
         && proxyPassword != null) {
       ((AbstractHttpClient) httpClient)
           .getCredentialsProvider()
           .setCredentials(
               new AuthScope(proxyHost, proxyPort),
               new UsernamePasswordCredentials(proxyUsername, proxyPassword));
     }
   }
 }
  public static void getSheng() {
    try {
      //			键	值
      //			请求	GET http://www.tudali.com/SelectShop/Index HTTP/1.1
      HttpClient httpclient = new DefaultHttpClient();
      HttpHost proxy = new HttpHost("192.168.19.9", 80);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      HttpGet httpget = new HttpGet("http://kfc.xixik.com/shop/beijing/jyj/");
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      String html = EntityUtils.toString(entity, "gbk");
      // System.out.println(html);
      String[] datas = html.split("id=\"footer\"")[0].split("class=\"char_char\"");
      for (int i = 1; i < datas.length; i++) {
        String[] hangs = datas[i].split("href=\"");
        for (int j = 2; j < hangs.length; j++) {
          String shiname = hangs[j].split(">")[1].split("<")[0].trim();
          String href = hangs[j].split("\"")[0];
          //					System.out.println(shiname+":"+href);
          getShi(shiname, href);
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
  public String executeHttpGet(String URL) throws Exception {
    BufferedReader in = null;
    try {
      HttpClient client = new DefaultHttpClient();
      client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
      HttpGet request = new HttpGet();
      request.setHeader("Content-Type", "text/plain; charset=utf-8");
      request.setURI(new URI(URL));
      HttpResponse response = client.execute(request);
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      StringBuffer sb = new StringBuffer("");
      String line = "";

      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();
      String page = sb.toString();
      // System.out.println(page);
      return page;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          Log.d("BBB", e.toString());
        }
      }
    }
  }
Exemplo n.º 15
0
  /**
   * 获取HttpClient,不同的业务场景传入不同的连接超时、请求超时参数
   *
   * @param url 访问的url
   * @param timeOut 连接超时
   * @param soTimeout 请求超时
   * @return HttpClient
   */
  public static HttpClient getHttpClient(String url, int timeOut, int soTimeout) {
    if (timeOut == 0) {
      timeOut = CONN_TIME_OUT;
    }
    if (soTimeout == 0) {
      soTimeout = SO_TIME_OUT;
    }

    StringBuilder sb = new StringBuilder(5);
    sb.append(url).append(".").append(timeOut).append(".").append(soTimeout);
    String key = sb.toString();

    HttpClient httpclient = httpClientMap.get(key);
    if (httpclient == null) {
      httpclient = new DefaultHttpClient(connectionManager);
      HttpParams params = httpclient.getParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
      params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
      HttpClient tempClient = httpClientMap.putIfAbsent(key, httpclient);
      if (tempClient != null) {
        httpclient = tempClient;
      }
    }

    return httpclient;
  }
Exemplo n.º 16
0
  public static HttpClient wrapClient(HttpClient base) {
    try {
      SSLContext ctx = SSLContext.getInstance("TLS");
      X509TrustManager tm =
          new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            public void checkServerTrusted(X509Certificate[] xcs, String string)
                throws CertificateException {}

            public X509Certificate[] getAcceptedIssuers() {
              return null;
            }
          };
      ctx.init(null, new TrustManager[] {tm}, null);
      SSLSocketFactory ssf = new SSLSocketFactory(ctx);
      ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      ClientConnectionManager ccm = base.getConnectionManager();
      SchemeRegistry sr = ccm.getSchemeRegistry();
      sr.register(new Scheme("https", ssf, 443));
      return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
      return null;
    }
  }
Exemplo n.º 17
0
  static {
    httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();

    // set the time out of the connection/ socket. and the cache size
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // set the connection manager factory
    params.setParameter(
        ClientPNames.CONNECTION_MANAGER_FACTORY,
        new ClientConnectionManagerFactory() {
          public ClientConnectionManager newInstance(
              HttpParams params, SchemeRegistry schemeRegistry) {
            return new ThreadSafeClientConnManager(params, schemeRegistry);
          }
        });

    // set the redirect, default is true
    HttpClientParams.setRedirecting(params, true);

    // set the client verion
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // set user-agent
    HttpProtocolParams.setUserAgent(params, "eoeWIKI_Android/0.9");
    // set the charset
    HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // set not activate Expect:100-Continue
    HttpProtocolParams.setUseExpectContinue(params, false);

    // set the version of the cookie
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
  }
Exemplo n.º 18
0
 /**
  * Envoie une photo vers la plateforme web
  *
  * @param filename Nom de la photo à envoyer
  */
 void envoiPhoto(String filename) {
   String TAG = "envoiPhoto";
   Log.i(TAG, "Envoie de la photo");
   File pictureFile = new File(filename); // On récupère le fichier image
   // Initialisation du client HTTP
   HttpClient httpClient = new DefaultHttpClient();
   httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
   /* Création de la requête POST. On lui donne en adresse l'adresse du serveur
   suivi de /upload. Le serveur mis en place pendant le projet attend
   une requête de ce type */
   HttpPost postRequest = new HttpPost("http://192.168.43.8:9001/upload");
   try {
     // Création de l'entité qui sera associée à la requête
     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     // On lui ajoute les champs "picture" et "email"
     // !!Attention, les noms "picture" et "email" ont leur importance, c'est ce
     // qu'attend le serveur
     entity.addPart("picture", new FileBody(((File) pictureFile), "image/jpeg"));
     entity.addPart(
         "email",
         new StringBody("*****@*****.**", "text/plain", Charset.forName("UTF-8")));
     postRequest.setEntity(entity); // Exécution de la requête
     String response = EntityUtils.toString(httpClient.execute(postRequest).getEntity(), "UTF-8");
     Log.i(TAG, "Requete exécutée");
   } catch (IOException e) {
     Log.i(TAG, "L'exécution de la requête lance une exception car : " + e.toString());
   }
   Log.i(TAG, "Sortie envoiPhoto");
 }
  public static void getShi(String shiname, String href) {
    try {
      //			键	值
      //			请求	POST
      // http://www.bank-of-tianjin.com.cn/websiteview/cityCascade/selectCityByparentId/dd4b857d3f684d79b4d89c55d54d10c9.json HTTP/1.1

      HttpClient httpclient = new DefaultHttpClient();
      HttpHost proxy = new HttpHost("192.168.19.9", 80);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      HttpGet httpget = new HttpGet("http://www.orangehotel.com.cn" + href);
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      String html = EntityUtils.toString(entity, "utf-8");
      //			System.out.println(html);
      String[] datas = html.split("内容一开始")[1].split("内容一结束 ")[0].split("href=\"");
      for (int i = 1; i < datas.length; i++) {
        String addr = datas[i].split("<h2>")[1].split("</h2>")[0];
        String url = datas[i].split("\"")[0];
        //				System.out.println(addr+":"+url);
        chuli(shiname, url);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 20
0
 /**
  * 获取SSL验证的HttpClient
  *
  * @param httpClient
  * @return
  */
 public static HttpClient getSSLInstance(HttpClient httpClient) {
   ClientConnectionManager ccm = httpClient.getConnectionManager();
   SchemeRegistry sr = ccm.getSchemeRegistry();
   sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
   httpClient = new DefaultHttpClient(ccm, httpClient.getParams());
   return httpClient;
 }
  public HttpClient getMockHttpClient() {
    HttpClient mock = Mockito.mock(HttpClient.class);
    HttpParams paramsMock = Mockito.mock(HttpParams.class);
    ClientConnectionManager connectionMock = Mockito.mock(ClientConnectionManager.class);
    HttpResponse hrMocked = Mockito.mock(HttpResponse.class);
    StatusLine slMocked = Mockito.mock(StatusLine.class);

    Header headerMocked = Mockito.mock(Header.class);

    Mockito.when(connectionMock.getSchemeRegistry())
        .thenReturn(SchemeRegistryFactory.createDefault());
    Mockito.when(hrMocked.getEntity()).thenReturn(heMocked);
    Mockito.when(mock.getParams()).thenReturn(paramsMock);
    Mockito.when(mock.getConnectionManager()).thenReturn(connectionMock);
    try {
      Mockito.when(mock.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)))
          .thenReturn(hrMocked);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Mockito.when(hrMocked.getStatusLine()).thenReturn(slMocked);
    Mockito.when(slMocked.getStatusCode()).thenReturn(200);
    Mockito.when(heMocked.getContentType()).thenReturn(headerMocked);
    Mockito.when(headerMocked.getElements()).thenReturn(new HeaderElement[0]);
    return mock;
  }
  public void tstPostImage() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://10.0.0.2:8080/rs/solve");
    File file = new File("/Users/alexwinston/Desktop/photo.PNG");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/png");
    mpEntity.addPart("image", 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 (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
  /**
   * Creates an HttpClient with the specified userAgent string.
   *
   * @param userAgent the userAgent string
   * @return the client
   */
  public static HttpClient newHttpClient(String userAgent) {
    // AndroidHttpClient is available on all platform releases,
    // but is hidden until API Level 8
    try {
      Class<?> clazz = Class.forName("android.net.http.AndroidHttpClient");
      Method newInstance = clazz.getMethod("newInstance", String.class);
      Object instance = newInstance.invoke(null, userAgent);

      HttpClient client = (HttpClient) instance;

      // ensure we default to HTTP 1.1
      HttpParams params = client.getParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

      // AndroidHttpClient sets these two parameters thusly by default:
      // HttpConnectionParams.setSoTimeout(params, 60 * 1000);
      // HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);

      // however it doesn't set this one...
      ConnManagerParams.setTimeout(params, 60 * 1000);

      return client;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
 private HttpClient getHttpClient() {
   if (null == customerHttpClient) {
     HttpParams params = new BasicHttpParams();
     // 设置一些基本参数
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUseExpectContinue(params, true);
     HttpProtocolParams.setUserAgent(params, "Linux; Android 2.2.1;zh-CN; itkt_Android");
     //			HttpClientParams.setRedirecting(params, true);
     //		    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
     // 设置最大连接数
     ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
     // 设置获取连接的最大等待时间
     ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
     // 设置每个路由最大连接数
     ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
     ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
     // 设置连接超时时间
     HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
     // 设置读取超时时间
     HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
     try {
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       SchemeRegistry schReg = new SchemeRegistry();
       schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       // 使用线程安全的连接管理来创建HttpClient
       ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
       customerHttpClient = new DefaultHttpClient(conMgr, params);
       customerHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return customerHttpClient;
 }
Exemplo n.º 25
0
  public static String visitPageAndGet(String url) {

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader(
        "User-Agent",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    try {
      httpResponse = httpClient.execute(httpGet);
      httpEntity = httpResponse.getEntity();
      String html = convertStreamToString(httpEntity.getContent());
      //            try {
      //                Thread.sleep(3000);
      //            } catch (InterruptedException e) {
      //                e.printStackTrace();
      //            }
      return html;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
 public static void sheng() {
   try {
     HttpClient httpclient = new DefaultHttpClient();
     HttpHost proxy = new HttpHost("192.168.19.9", 80);
     httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
     HttpGet httpget = new HttpGet("http://www.orangehotel.com.cn/beijing/");
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity entity = response.getEntity();
     String html = EntityUtils.toString(entity, "utf-8");
     //			System.out.println(html);
     String[] datas = html.split("class=\"usp_list\"")[1].split("</div>")[0].split("href=\"");
     for (int i = 1; i < datas.length; i++) {
       String shiname = datas[i].split(">")[1].split("<")[0].substring(0, 2);
       String href = datas[i].split("\"")[0];
       if (shiname.equals("秦皇")) {
         shiname = "秦皇岛";
       }
       if (shiname.equals("连云")) {
         shiname = "连云港";
       }
       //				System.out.println(shiname+":"+href);
       getShi(shiname, href);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 27
0
 public String addVideo(String json, InputStream is, String fileName)
     throws ClientProtocolException, IOException {
   HttpClient httpclient = getHttpClient();
   try {
     File video = new File(fileName);
     OutputStream out = new FileOutputStream(video);
     IOUtils.copy(is, out);
     httpclient
         .getParams()
         .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
     HttpPost post = new HttpPost(BC_MEDIA_URL);
     MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     ContentBody content =
         new FileBody(video, new MimetypesFileTypeMap().getContentType(fileName));
     multipart.addPart("JSON-RPC", new StringBody(json));
     multipart.addPart("file", content);
     post.setEntity(multipart);
     HttpResponse response = httpclient.execute(post);
     HttpEntity entity = response.getEntity();
     if (entity != null) {
       String result = EntityUtils.toString(entity);
       return result;
     }
   } finally {
     httpclient.getConnectionManager().shutdown();
   }
   return "";
 }
  /**
   * Wrap a basic HttpClient object in an all trusting SSL enabled HttpClient object.
   *
   * @param base The HttpClient to wrap.
   * @return The SSL wrapped HttpClient.
   * @throws GeneralSecurityException
   * @throws IOException
   */
  private HttpClient trustAllSslEnable(HttpClient base) throws GeneralSecurityException {
    // Get an initialized SSL context
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}
          }
        };

    // set up the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL"); // $NON-NLS-1$
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); // $NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
  }
Exemplo n.º 29
0
  /**
   * get请求
   *
   * @param context
   * @param url
   * @param params
   * @param responseListener
   * @throws IOException
   * @throws Exception
   */
  public static InputStream request(Context context, String url, Bundle params)
      throws IOException, Exception {

    if (params != null) {
      if (url.contains("?")) {
        url = url + "&" + UrlUtils.encodeUrl(params);
      } else {
        url = url + "?" + UrlUtils.encodeUrl(params);
      }
    }

    Logger.getLogger().d("GET:" + url);

    HttpGet request = new HttpGet(url);
    HttpClient httpClient = getInstance(context);

    // 解决:HttpClient WARNING: Cookie rejected: Illegal domain attribute
    httpClient
        .getParams()
        .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpResponse response;
    InputStream in = null;
    response = httpClient.execute(request);
    in = response.getEntity().getContent();

    return in;
  }
  private void executeRequest(HttpUriRequest request, String url) {
    HttpClient client = new DefaultHttpClient(httpRequestParams);
    client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, BUFFER_SIZE);
    HttpResponse httpResponse;

    try {
      httpResponse = client.execute(request);
      responseCode = httpResponse.getStatusLine().getStatusCode();
      message = httpResponse.getStatusLine().getReasonPhrase();

      HttpEntity entity = httpResponse.getEntity();

      if (entity != null) {

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

        // Closing the input stream will trigger connection release
        instream.close();
      }

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