private static HttpClient createClient() {
    // create timeouts
    HttpParams httpParams = new BasicHttpParams();
    // throws java.net.ConnectTimeoutException: Socket is not connected
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    // throws java.net.SocketTimeoutException: Read timed out
    HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);

    HttpClient client = null;
    //        if (!_sslValidateCert) {
    client = createUnsecureClient(httpParams);
    //        } else {
    //            // Create and initialize scheme registry
    //            SchemeRegistry schemeRegistry = new SchemeRegistry();
    //            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(),
    // 80));
    //            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(),
    // 443));
    //
    //            ClientConnectionManager cm = new SingleClientConnManager(httpParams,
    // schemeRegistry);
    //            client = new DefaultHttpClient(cm, httpParams);
    //        }

    return client;
  }
  private String doGet(String url) {
    String responseStr = "";
    try {
      HttpGet httpRequest = new HttpGet(url);
      HttpParams params = new BasicHttpParams();
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 3000);
      HttpConnectionParams.setSoTimeout(params, 5000);
      httpRequest.setParams(params);

      HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
      final int ret = httpResponse.getStatusLine().getStatusCode();
      if (ret == HttpStatus.SC_OK) {
        responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
      } else {
        responseStr = "-1";
      }
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return responseStr;
  }
Example #3
0
 private void SetupHTTPConnectionParams(HttpUriRequest method) {
   HttpConnectionParams.setConnectionTimeout(method.getParams(), CONNECTION_TIMEOUT_MS);
   HttpConnectionParams.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
   // mClient.setHttpRequestRetryHandler(requestRetryHandler);
   method.addHeader("Accept-Encoding", "gzip, deflate");
   method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
 }
Example #4
0
    private void sendMessage(final String suffix, final HttpEntity message) throws SenderException {
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
      HttpConnectionParams.setSoTimeout(httpParams, 5000);
      HttpClient httpClient = new DefaultHttpClient(httpParams);

      HttpPost httppost = new HttpPost(url + "/" + suffix + "/" + buildId);
      if (message != null) {
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf");
        httppost.setEntity(message);
      }
      if (!secret.isEmpty()) {
        httppost.setHeader(DASH_SECRET_HEADER, secret);
      }
      StatusLine status;
      try {
        status = httpClient.execute(httppost).getStatusLine();
      } catch (IOException e) {
        throw new SenderException("Error sending results to " + url, e);
      }
      if (status.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new SenderException(
            "Permission denied while sending results to "
                + url
                + ". Did you specified --dash_secret?");
      }
    }
Example #5
0
 private static HttpClient a()
 {
     BasicHttpParams basichttpparams = new BasicHttpParams();
     HttpConnectionParams.setConnectionTimeout(basichttpparams, 30000);
     HttpConnectionParams.setSoTimeout(basichttpparams, 30000);
     return new DefaultHttpClient(basichttpparams);
 }
  /**
   * HttpClient方式实现,支持验证指定证书
   *
   * @throws ClientProtocolException
   * @throws IOException
   */
  public void initSSLCertainWithHttpClient() throws ClientProtocolException, IOException {
    int timeOut = 30 * 1000;
    HttpParams param = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(param, timeOut);
    HttpConnectionParams.setSoTimeout(param, timeOut);
    HttpConnectionParams.setTcpNoDelay(param, true);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", TrustCertainHostNameFactory.getDefault(this), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);
    DefaultHttpClient client = new DefaultHttpClient(manager, param);

    // HttpGet request = new
    // HttpGet("https://certs.cac.washington.edu/CAtest/");
    HttpGet request = new HttpGet("https://www.alipay.com/");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder result = new StringBuilder();
    String line = "";
    while ((line = reader.readLine()) != null) {
      result.append(line);
    }
    Log.e("HTTPS TEST", result.toString());
  }
 /**
  * Creates an instance of {@link HttpClient}, with a defined timeout, to be used for all of the
  * method calls within the class.
  *
  * @param timeout An {@link Integer} value indicating the time in milliseconds to wait before
  *     considering a request to have timed out.
  * @return An instance of {@link HttpClient}, pre-configured with the timeout value supplied.
  */
 private HttpClient getGenericHttpClient(int timeout) {
   if (timeout <= 0) timeout = DEFAULT_TIMEOUT;
   HttpParams httpParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
   HttpConnectionParams.setSoTimeout(httpParams, timeout);
   return new DefaultHttpClient(httpParams);
 }
Example #8
0
    @Override
    protected String doInBackground(Void... params) {
      ArrayList<NameValuePair> inputData = new ArrayList<>();
      inputData.add(new BasicNameValuePair("isLike", "" + isLike));
      inputData.add(new BasicNameValuePair("userId", userId));
      inputData.add(new BasicNameValuePair("postId", postId));
      Log.d("like", "do in background");
      HttpParams httpRequestParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

      HttpClient client = new DefaultHttpClient(httpRequestParams);
      HttpPost post = new HttpPost(SERVER_ADDRESS + "like.php");
      Log.d("like", "connected");

      try {
        post.setEntity(new UrlEncodedFormEntity(inputData));
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        String strEntity = EntityUtils.toString(entity);
        Log.d("like", strEntity);
        JSONObject j = new JSONObject(strEntity);
        message = j.getString("message");
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
      Log.d("like", "returned");
      return message;
    }
Example #9
0
    @Override
    protected ArrayList<Marker> doInBackground(Void... params) {
      HttpParams httpRequestParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

      HttpClient client = new DefaultHttpClient(httpRequestParams);
      HttpPost post = new HttpPost(SERVER_ADDRESS + "getMarker.php");
      Log.d("feed", "connected");
      ArrayList<Marker> listMarker = new ArrayList<>();
      try {
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        String strEntity = EntityUtils.toString(entity);
        Log.d("feed", strEntity);
        JSONObject json = new JSONObject(strEntity);
        JSONArray jsonArray = json.getJSONArray("post");
        for (int i = 0; i < jsonArray.length(); i++) {
          JSONObject jsonobject = jsonArray.getJSONObject(i);
          String id = jsonobject.getString("id");
          double latitude = jsonobject.getDouble("latitude");
          double longitude = jsonobject.getDouble("longitude");
          Marker marker = new Marker(id, latitude, longitude);
          listMarker.add(marker);
        }
      } catch (Exception e) {
        Log.d("feed", "exception");
        e.printStackTrace();
        return null;
      }
      Log.d("feed", "returned");
      return listMarker;
    }
Example #10
0
    @Override
    protected List<PostItem> doInBackground(Void... params) {
      ArrayList<NameValuePair> inputData = new ArrayList<>();
      inputData.add(new BasicNameValuePair("numFeed", "" + numFeed));
      inputData.add(new BasicNameValuePair("userId", userId));
      Log.d("feed", "do in background");
      HttpParams httpRequestParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

      HttpClient client = new DefaultHttpClient(httpRequestParams);
      HttpPost post = new HttpPost(SERVER_ADDRESS + "getFeed.php");
      Log.d("feed", "connected");
      List<PostItem> listPostItem = new ArrayList<>();
      try {
        post.setEntity(new UrlEncodedFormEntity(inputData));
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        String strEntity = EntityUtils.toString(entity);
        Log.d("feed", strEntity);
        JSONObject json = new JSONObject(strEntity);
        JSONArray jsonArray = json.getJSONArray("post");
        for (int i = 0; i < jsonArray.length(); i++) {
          JSONObject jsonobject = jsonArray.getJSONObject(i);
          String id = jsonobject.getString("id");
          String link = jsonobject.getString("link");
          String linkSmall = jsonobject.getString("linkSmall");
          String description = jsonobject.getString("description");
          String name = jsonobject.getString("name");
          String time = jsonobject.getString("time");
          int totalLike = jsonobject.getInt("totalLike");
          boolean isLike = jsonobject.getBoolean("isLike");
          String address = jsonobject.getString("address");
          double latitude = jsonobject.getDouble("latitude");
          double longitude = jsonobject.getDouble("longitude");
          PostItem postItem =
              new PostItem(
                  id,
                  null,
                  name,
                  time,
                  link,
                  linkSmall,
                  description,
                  totalLike,
                  isLike,
                  address,
                  latitude,
                  longitude);
          listPostItem.add(postItem);
        }

      } catch (Exception e) {
        Log.d("feed", "exception");
        e.printStackTrace();
        return null;
      }
      Log.d("feed", "returned");
      return listPostItem;
    }
Example #11
0
    @Override
    protected String[] doInBackground(Void... params) {
      ArrayList<NameValuePair> inputData = new ArrayList<>();
      inputData.add(new BasicNameValuePair("id", id));
      inputData.add(new BasicNameValuePair("newPassword", newPassword));
      inputData.add(new BasicNameValuePair("oldPassword", oldPassword));
      Log.d("change", "do in background");
      HttpParams httpRequestParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

      HttpClient client = new DefaultHttpClient(httpRequestParams);
      HttpPost post = new HttpPost(SERVER_ADDRESS + "changePassword.php");
      Log.d("change", "connected");

      try {
        post.setEntity(new UrlEncodedFormEntity(inputData));
        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        String strEntity = EntityUtils.toString(entity);
        Log.d("change", strEntity);
        JSONObject j = new JSONObject(strEntity);
        result[0] = "" + j.getBoolean("isSuccess");
        result[1] = j.getString("message");

      } catch (Exception e) {
        e.printStackTrace();
      }
      Log.d("change", "returned");
      return result;
    }
Example #12
0
  public static String requestWithPost(String postURL, Map<String, String> m_params) {
    try {
      HttpParams httpParameters = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

      List<NameValuePair> params = new ArrayList<NameValuePair>();

      if (m_params != null) {
        for (String key : m_params.keySet()) {
          params.add(new BasicNameValuePair(key, m_params.get(key)));
        }
      }

      HttpClient client = new DefaultHttpClient(httpParameters);
      HttpPost post = new HttpPost(postURL);

      UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
      post.setEntity(ent);
      HttpResponse responsePOST = client.execute(post);
      HttpEntity resEntity = responsePOST.getEntity();

      if (resEntity != null) {
        String result = EntityUtils.toString(resEntity);
        Log.d("NETWORK_RESULT", result);
        return result;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
    @Override
    protected String doInBackground(String... urls) {
      String output = "";
      HttpGet httpGet = null;
      DefaultHttpClient httpClient = null;
      HttpParams httpParameters = new BasicHttpParams();
      int timeoutConnection = 3000;
      int timeoutSocket = 5000;
      HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
      try {
        httpClient = new DefaultHttpClient(httpParameters);
        URI url = new URI(urls[0]);
        httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        output = EntityUtils.toString(httpEntity);

        output = output.replaceAll("\\r\\n\\t|\\r|\\n|\\t", "");

      } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
      }
      return output;
    }
Example #14
0
 private Response handleHttpRequest(HttpRequestBase httpRequestBase) throws IOException {
   HttpParams httpParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
   HttpConnectionParams.setSoTimeout(httpParams, timeout);
   HttpClient httpClient = new DefaultHttpClient(httpParams);
   byte[] content = null;
   String charset;
   HttpResponse httpResponse;
   Header cookie;
   try {
     httpResponse = httpClient.execute(httpRequestBase);
     cookie = httpResponse.getLastHeader("Set-Cookie");
     //			Log.d("remote", "cookie: " + cookie);
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null) {
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       InputStream is = httpEntity.getContent();
       IoUtil.ioAndClose(is, bos);
       content = bos.toByteArray();
     }
     charset = EntityUtils.getContentCharSet(httpEntity);
   } finally {
     try {
       httpClient.getConnectionManager().shutdown();
     } catch (Exception ignore) {
       // ignore it
     }
   }
   return responseParser.parse(content, charset, parseSessionId(cookie));
 }
Example #15
0
  public HttpUtils(int connTimeout, String userAgent) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    if (TextUtils.isEmpty(userAgent)) {
      userAgent = OtherUtils.getUserAgent(null);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
              httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                  response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                  return;
                }
              }
            }
          }
        });
  }
  private static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

      SSLSocketFactory sf = new MySSLSocketFactory(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);
      HttpConnectionParams.setConnectionTimeout(params, 10000);
      HttpConnectionParams.setSoTimeout(params, 20000);

      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();
    }
  }
  private HttpResponse HttpClientPost(String URL, String upload) {
    BasicHttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    HttpClient httpclient = new DefaultHttpClient(httpParams);
    try {
      HttpPost post = new HttpPost(URL);
      post.addHeader("content-type", "application/x-www-form-urlencoded");
      post.setEntity(new StringEntity(upload));

      HttpResponse response = httpclient.execute(post);
      return response;
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
  private HttpClient newHttpClient(String sslProtocol, HttpRequest request) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, httpTimeoutsProvider.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params, httpTimeoutsProvider.getSocketTimeout());

    // AG-1059: Need to follow redirects to ensure that if the host app is setup with Apache and
    // mod_jk we can still
    // fetch internal gadgets.
    if (request.getFollowRedirects()) {
      params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
      params.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);
    }
    params.setParameter(
        ClientPNames.DEFAULT_HEADERS,
        ImmutableSet.of(new BasicHeader("Accept-Encoding", "gzip, deflate")));
    DefaultHttpClient client = new DefaultHttpClient(params);
    // AG-1044: Need to use the JVM's default proxy configuration for requests.
    ProxySelectorRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);

    client.addResponseInterceptor(new GzipDeflatingInterceptor());
    client
        .getConnectionManager()
        .getSchemeRegistry()
        .register(new Scheme("https", new CustomSSLSocketFactory(sslProtocol), 443));
    return client;
  }
Example #19
0
  public static synchronized HttpClient getHttpClient() {
    if (null == customerHttpClient) {
      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params,
          "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
              + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

      // 从连接池中取连续的超时时间
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 2000);
      HttpConnectionParams.setSoTimeout(params, 4000);

      // 设置我们的HttpClient支持HTTP和HTTPS两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
      customerHttpClient = new DefaultHttpClient(conMgr, params);
    }
    return customerHttpClient;
  }
Example #20
0
 public HttpUtils configTimeout(int timeout) {
   final HttpParams httpParams = this.httpClient.getParams();
   ConnManagerParams.setTimeout(httpParams, timeout);
   HttpConnectionParams.setSoTimeout(httpParams, timeout);
   HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
   return this;
 }
Example #21
0
 public String httpPost(String url, List<Parameter> params) throws Exception {
   String response = null;
   int timeoutConnection = 3000;
   int timeoutSocket = 5000;
   String Url = "http://www.kan-shu.cn" + url;
   HttpParams httpParameters =
       new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established.
   HttpConnectionParams.setConnectionTimeout(
       httpParameters,
       timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which
                           // is the timeout for waiting for data.
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
   HttpClient httpClient = new DefaultHttpClient(httpParameters);
   HttpPost httpPost = new HttpPost(Url);
   if (params.size() >= 0) {
     httpPost.setEntity(new UrlEncodedFormEntity(buildNameValuePair(params), HTTP.UTF_8));
   }
   HttpResponse httpResponse = httpClient.execute(httpPost);
   int statusCode = httpResponse.getStatusLine().getStatusCode();
   if (statusCode == HttpStatus.SC_OK) {
     response = EntityUtils.toString(httpResponse.getEntity());
   } else {
     response = "状态码" + statusCode;
   }
   return response;
 }
  /**
   * Create a new HttpClient with reasonable defaults (which you can update).
   *
   * @param userAgent to report in your HTTP requests.
   * @return FailfastHttpClient for you to use for all your requests.
   */
  public static FailfastHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // 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 10 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null) HttpProtocolParams.setUserAgent(params, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new FailfastHttpClient(manager, params);
  }
Example #23
0
 protected MjpegInputStream doInBackground(String... url) {
   // TODO: if camera has authentication deal with it and don't just not work
   HttpResponse res = null;
   DefaultHttpClient httpclient = new DefaultHttpClient();
   HttpParams httpParams = httpclient.getParams();
   HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000);
   HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000);
   if (DEBUG) Log.d(TAG, "1. Sending http request");
   try {
     res = httpclient.execute(new HttpGet(URI.create(url[0])));
     if (DEBUG)
       Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode());
     if (res.getStatusLine().getStatusCode() == 401) {
       // You must turn off camera User Access Control before this will work
       return null;
     }
     return new MjpegInputStream(res.getEntity().getContent());
   } catch (ClientProtocolException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "Request failed-ClientProtocolException", e);
     }
     // Error connecting to camera
   } catch (IOException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "Request failed-IOException", e);
     }
     // Error connecting to camera
   }
   return null;
 }
Example #24
0
    @Override
    protected Void doInBackground(ArrayList... params) {
      try {
        String fileLocation = String.valueOf(params[0].get(0));
        String fileName = String.valueOf(params[0].get(1));
        String folder = String.valueOf(params[0].get(2));

        String path = Constants.ASSETS_IP + fileLocation + fileName;
        URL u = new URL(path);
        HttpParams httpParameters = new BasicHttpParams();
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        int timeoutConnection = 3000;
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        InputStream is = c.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File(folder + "/" + fileName));
        int bytesRead = 0;
        byte[] buffer = new byte[4096];
        while ((bytesRead = is.read(buffer)) != -1) {
          fos.write(buffer, 0, bytesRead);
        }
        fos.close();
        is.close();
        c.disconnect();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }
Example #25
0
  public Document getDocument(
      double fromLatitude, double fromLongitude, GeoPoint toPosition, String mode)
      throws Exception {
    String url =
        "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin="
            + fromLatitude
            + ","
            + fromLongitude
            + "&destination="
            + toPosition.lat
            + ","
            + toPosition.lng
            + "&sensor=false&units=metric&mode="
            + mode;

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); // 20seconds
    HttpConnectionParams.setSoTimeout(httpParameters, 20000); // 20 seconds

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    HttpContext localContext = new BasicHttpContext();

    HttpResponse response = httpClient.execute(httpPost, localContext);

    InputStream in = response.getEntity().getContent();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(in);
    return doc;
  }
Example #26
0
  /**
   * 通过delete方式发送请求 删除农场
   *
   * @param url URL地址
   * @param params 参数 user_serial, password, farm_serial
   * @return
   * @throws Exception
   */
  public String httpdeleteFarm(String url, String tokenAuth) throws Exception {
    // 拼接请求URL
    int timeoutConnection = YunTongXun.httpclienttime;
    int timeoutSocket = YunTongXun.httpclienttime;
    HttpParams httpParameters =
        new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(
        httpParameters,
        timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which
                            // is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // 构造HttpClient的实例
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    // 创建GET方法的实例
    HttpDelete httpexit = new HttpDelete(url);
    httpexit.setHeader("Authorization", tokenAuth);
    try {
      HttpResponse httpResponse = httpClient.execute(httpexit);
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      return "{status_code:" + statusCode + "}";

    } catch (Exception e) {
      return null;
    }
  }
  private void initQuery() throws IOException {
    Hashtable<String, String> map = new Hashtable<String, String>();
    map.put("uid", "TEMP_USER");
    map.put("pwd", "TEMP_PASSWORD");
    map.put(QUERY_PARAM, Base64.encodeToString(TEST_QUERY.getBytes(), 0));

    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create post method
    HttpPost postMethod = new HttpPost(QUERY_URI);

    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    ObjectOutputStream objOS = new ObjectOutputStream(byteArrayOS);
    objOS.writeObject(map);
    ByteArrayEntity req_entity = new ByteArrayEntity(byteArrayOS.toByteArray());
    req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

    // associating entity with method
    postMethod.setEntity(req_entity);

    // Executing post method
    executeHttpClient(httpClient, postMethod);
  }
Example #28
0
    @Override
    // Run in the background when StoreUserDataAsyncTask starts - Accessing the server
    protected Void doInBackground(Void... params) {
      // Data which are send to server
      ArrayList<NameValuePair> dataToSend = new ArrayList<>();
      dataToSend.add(new BasicNameValuePair("name", user.name));
      dataToSend.add(new BasicNameValuePair("username", user.username));
      dataToSend.add(new BasicNameValuePair("password", user.password));
      dataToSend.add(new BasicNameValuePair("email", user.email));

      HttpParams httpRequestParams = new BasicHttpParams();
      // Time to wait before the post is executed
      HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIME);
      // Time to wait to receive anything from server
      HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIME);

      // Create client to establish HTTP connection + and make request to server
      HttpClient client = new DefaultHttpClient(httpRequestParams);
      HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

      try {
        post.setEntity(new UrlEncodedFormEntity(dataToSend));
        client.execute(post);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }
Example #29
0
  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    try {
      StringEntity se;
      // Log.e("http string",URL+"//"+send.toString());
      HttpParams httpParameters = new BasicHttpParams(); // set connection parameters
      HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
      HttpConnectionParams.setSoTimeout(httpParameters, 60000);
      HttpClient httpclient = new DefaultHttpClient(httpParameters);
      HttpResponse response = null;
      HttpPost httppost = new HttpPost(params[0]);
      httppost.setHeader("Content-type", "application/json");
      se = new StringEntity(params[1]);
      se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      httppost.setEntity(se);
      response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      InputStream is = entity.getContent();
      streamtostring(is);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Example #30
0
  public static String post(String host, List<BasicNameValuePair> params, String encoding) {
    HttpPost httpPost = new HttpPost(host);
    try {

      BasicHttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
      HttpConnectionParams.setSoTimeout(httpParams, 5000);

      DefaultHttpClient client = new DefaultHttpClient(httpParams);

      UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(params, encoding);
      httpPost.setEntity(p_entity);
      HttpResponse response = client.execute(httpPost);

      String result = "";
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == 200) {
        result = EntityUtils.toString(response.getEntity(), encoding);
      }

      return result;

    } catch (Exception e) {

      return "";
    }
  }