Beispiel #1
0
 public static <T> T doPostSync(RequestParams params, Class<T> responseCls) throws TaskException {
   try {
     return x.http().postSync(params, responseCls);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
Beispiel #2
0
 /**
  * 下载文件
  *
  * @param params 请求参数
  * @param filepath 保存路径
  */
 public static File downloadFile(RequestParams params, String filepath) throws TaskException {
   // 设置断点续传
   params.setAutoResume(true);
   params.setSaveFilePath(filepath);
   try {
     return x.http().getSync(params, File.class);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
    protected String doInBackground(String... params) {
      Log.i(TAG, "doInBackground");
      String respuesta = null;

      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String IMEI = telephonyManager.getDeviceId();
        String IMSI = telephonyManager.getSimSerialNumber();
        String consulta;
        if (phone.getText().toString().equals("2")) {
          consulta = URLs.RESOURCE;
        } else consulta = SoapRequestMovistar.getResource(IMEI, IMSI, phone.getText().toString());

        ArrayList<String> retorno = XMLParser.getReturnCode(consulta);

        code = Integer.valueOf(retorno.get(0));

        if (code == 0) {
          respuesta = consulta;
          Log.i(TAG, retorno.get(1));
        } else respuesta = retorno.get(1);
        return respuesta;

      } catch (HttpHostConnectException e2) {
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (HttpResponseException e3) {
        e3.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ParseException p) {
        p.printStackTrace();
        errorMessage = "Error en la recepción de los datos. Por favor reintente";
        return null;
      } catch (SocketTimeoutException s1) {
        s1.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ConnectTimeoutException et) {
        et.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (Exception e1) {
        e1.printStackTrace();
        errorMessage = "Ha ocurrido un error con la respuesta del servidor.";
        return null;
      }
    }
Beispiel #4
0
 @Override
 public void onConnectTimeoutException(ConnectTimeoutException e, Object arg1) {
   Message msg = new Message();
   Bundle params = new Bundle();
   params.putString("response", e.getMessage());
   params.putString("title", "onConnectTimeoutException");
   mHandler.sendMessage(msg);
 }
 public JSONArray getArray(String path, ArrayList<NameValuePair> params) {
   JSONArray res = new JSONArray();
   String paramString = URLEncodedUtils.format(params, "utf-8");
   HttpGet httpGet = new HttpGet(host + ":" + port + path + "?" + paramString);
   HttpResponse response;
   try {
     response = httpClient.execute(httpGet);
     res = new JSONArray(EntityUtils.toString(response.getEntity()));
   } catch (ConnectTimeoutException c) {
     c.printStackTrace();
   } catch (SocketTimeoutException s) {
     s.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return res;
 }
 public JSONObject put(String path, ArrayList<NameValuePair> params) {
   JSONObject res = new JSONObject();
   HttpPut httpPut = new HttpPut(host + ":" + port + path);
   try {
     httpPut.setEntity(new UrlEncodedFormEntity(params));
     HttpResponse response;
     response = httpClient.execute(httpPut);
     res = new JSONObject(EntityUtils.toString(response.getEntity()));
   } catch (ConnectTimeoutException c) {
     c.printStackTrace();
   } catch (SocketTimeoutException s) {
     s.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return res;
 }
  /**
   * Send synchronous request to HTTP server.
   *
   * @param method request method (GET or POST).
   * @param params set of pairs <key, value>, fields.
   * @param listenr interface (callback) to bind to external classes.
   * @return response of HTTP Server.
   */
  private String HTTPSyncRequest(Methods method, JSONObject params, OnHTTPRequest listenr) {
    Log.i(LOG_TAG, "HTTPSyncRequest(" + method + ")");

    List<NameValuePair> requestParams = null;
    HttpRequestBase httpRequest = null;
    OnHTTPRequest listener = listenr;

    try {
      requestParams = jsonToList(params);
    } catch (JSONException e1) {
      e1.printStackTrace();
    }
    // Set parameters of HTTP request.
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    // Create a new HttpClient and Header
    HttpClient httpclient = new DefaultHttpClient(httpParameters);

    if (method == Methods.GET) {
      httpRequest = new HttpGet(URLServer + "?" + URLEncodedUtils.format(requestParams, "utf-8"));
    } else {
      httpRequest = new HttpPost(URLServer);

      // Add data to request
      try {
        ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(requestParams));
      } catch (UnsupportedEncodingException e) {
        listener.OnResquestError(e.getMessage().toString());
        e.printStackTrace();
      }
    }

    try {
      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httpRequest);

      Log.i(LOG_TAG, "Code: " + response.getStatusLine().getStatusCode());

      // Response
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return getHTTPResponseContent(response);
      } else {
        listener.OnResquestError("Server Error");
      }

    } catch (SocketTimeoutException e) {
      listener.OnResquestError("Socket Timeout" + e.getMessage().toString());
      Log.e(LOG_TAG, "Socket Timeout", e);
    } catch (ConnectTimeoutException e) {
      listener.OnResquestError("Connect Timeout" + e.getMessage().toString());
      Log.e(LOG_TAG, "Connect Timeout", e);
    } catch (ClientProtocolException e) {
      listener.OnResquestError("HTTP Error: " + e.getMessage().toString());
      Log.e(LOG_TAG, "HTTP Error", e);
    } catch (IOException e) {
      listener.OnResquestError("Connection Error: " + e.getMessage().toString());
      Log.e(LOG_TAG, "Connection Error", e);
    }

    return null;
  }
Beispiel #8
0
    @Override
    // protected String doInBackground(Void... arg0) {
    protected String doInBackground(String... params) {

      // String id = myApplication.getId();

      StringBuilder builder = new StringBuilder();
      ConnectUtils connector = new ConnectUtils();
      HttpClient client = connector.getNewHttpClient();
      String gender = params[0];

      if (Integer.valueOf(gender) == 1) {
        // male
        genderType = Globals.male;
      } else {
        // female
        genderType = Globals.female;
      }

      String result = "FAILED";

      // date

      // LOAD SERVER PREF

      try {
        sendString =
            "http://afuriqa.com/loco/addSettings.php?id="
                + URLEncoder.encode(prefs.getString(Globals.userId, null), "UTF-8")
                + "&weight="
                + URLEncoder.encode(tvWeight.getText().toString(), "UTF-8")
                + "&gender="
                + URLEncoder.encode(genderType, "UTF-8");
      } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      HttpGet httpGet = new HttpGet(sendString);

      try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
          HttpEntity entity = response.getEntity();
          InputStream content = entity.getContent();
          BufferedReader reader = new BufferedReader(new InputStreamReader(content));
          String line;
          while ((line = reader.readLine()) != null) {
            builder.append(line);
          }
          result = builder.toString();

        } else {

        }
      } catch (ConnectTimeoutException e) {

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

      return result;

      //

    }
    @Override
    public void run() {
      if (mCancel) {
        return;
      }
      try {
        Response response =
            Response.parseFrom(
                Base64.decodeBase64(
                    ConvertUtils.InputStreamToByte(
                        HttpRequest.request(mAppInfoForManage.getAppId(), which))));
        if (mCancel) {
          return;
        }
        image = response.getImageResponse().getImageData().toByteArray();
        if (mCancel) {
          return;
        }
        if (which == 0) {
          runOnUiThread(
              new Runnable() {

                public void run() {
                  if (mCancel) {
                    return;
                  }
                  try {
                    try {
                      bitMapOne = BitmapFactory.decodeByteArray(image, 0, image.length);
                    } catch (OutOfMemoryError oome) {
                      oome.printStackTrace();
                    }

                    if (mCancel) {
                      bitmapList.add(bitMapOne);
                      return;
                    }

                    mScreenshotOne.setImageBitmap(bitMapOne);
                    image = null;
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              });
        } else if (which == 1) {
          runOnUiThread(
              new Runnable() {
                @Override
                public void run() {
                  if (mCancel) {
                    return;
                  }
                  try {

                    try {
                      bitMapTwo = BitmapFactory.decodeByteArray(image, 0, image.length);
                    } catch (OutOfMemoryError oome) {
                      oome.printStackTrace();
                    }

                    if (mCancel) {
                      bitmapList.add(bitMapTwo);
                      return;
                    }

                    mScreenshotTwo.setImageBitmap(bitMapTwo);
                    image = null;
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              });
        }

      } catch (ConnectTimeoutException e) {
        e.printStackTrace();
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
      }
    }
  @SuppressWarnings("unused")
  private void postRemoteRes(String url, final String data) {
    try {
      // 设置HttpClient超时参数
      HttpParams httpParameters = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);

      DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); // 创建http
      // client
      HttpPost httpPost = new HttpPost(url); // 创建http post
      AbstractHttpEntity entity = null;

      ContentProducer cp =
          new ContentProducer() {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
              // outstream.write(data.getBytes(HTTP.UTF_8));
              // outstream.flush();
              // outstream.close();
              Writer writer = new OutputStreamWriter(outstream, "UTF-8");
              writer.write(data);
              writer.flush();
              writer.close();
            }
          };
      entity = new EntityTemplate(cp);

      entity = new StringEntity(data, "utf-8");

      entity =
          new InputStreamEntity(
              new ByteArrayInputStream(data.getBytes(HTTP.UTF_8)),
              data.getBytes(HTTP.UTF_8).length);

      entity.setContentType("application/x-www-form-urlencoded");
      entity.setContentEncoding("utf-8");
      httpPost.setEntity(entity);

      // HttpResponse httpResponse = httpClient.execute(httpPost);//
      // 执行http 请求

      URL urls = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
      conn.setConnectTimeout(CONNECTION_TIMEOUT);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      OutputStream out = conn.getOutputStream();

      // 默认参数方式传递
      out.write(data.getBytes(HTTP.UTF_8));
      out.flush();
      out.close();
      InputStream is = conn.getInputStream();
      if (is != null) {

        // if (httpResponse != null
        // && httpResponse.getStatusLine().getStatusCode() ==
        // HttpStatus.SC_OK) {
        // InputStream is = httpResponse.getEntity().getContent();

        byte[] buffer = new byte[512];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readLength = 0;
        int offset = 0;
        mDataLen = 0;
        mDataRes = null;
        do {
          readLength = is.read(buffer);
          if (readLength > 0) {
            baos.write(buffer, 0, readLength);
            offset += readLength;
            mDataLen = offset;
          }
        } while (!mIsStopDl && readLength > 0);
        mDataRes = baos.toByteArray();
        baos.close();
        is.close();
      }

      // 下载完成
      Log.i(
          TAG,
          "downloadRemoteRes download completed. data length="
              + (mDataRes == null ? "null" : mDataRes.length)
              + " record length="
              + mDataLen
              + " url="
              + url);
      if (!mIsStopDl && (mDataRes == null || mDataRes.length == 0)) {
        Log.e(TAG, "data = null");
        if (mDlListener != null) mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_RESULT_NULL);
        return;
      }
      if (!mIsStopDl && mDlListener != null) {
        Log.d(TAG, "downloadRemoteRes ---- callback in.");
        mDlListener.onDlCompleted(mTaskTag, mDataRes, mDataLen);
        Log.d(TAG, "downloadRemoteRes ---- callback out.");
      }
    } catch (ConnectTimeoutException e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_TIME_OUT);
      }
    } catch (SocketTimeoutException e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_TIME_OUT);
      }
    } catch (Exception e) {
      Log.e(TAG, "downloadRemoteRes exception url=" + url + " msg=" + e.getMessage());
      if (!mIsStopDl && mDlListener != null) {
        mDlListener.onDlError(mTaskTag, DownloadManager.ERROR_OTHER);
      }
    }
  }