Пример #1
0
  public static String postFile(
      String host, List<BasicNameValuePair> params, String fileName, String encoding) {
    HttpPost post = new HttpPost(host);
    try {
      File file = new File(fileName);
      MultipartEntity multipart = new MultipartEntity();
      for (BasicNameValuePair pair : params) {
        multipart.addPart(
            pair.getName(), new StringBody(pair.getValue(), Charset.forName(HTTP.UTF_8)));
      }

      multipart.addPart("file", new FileBody(file, "*/*", HTTP.UTF_8));
      HttpClient client = new DefaultHttpClient();
      post.addHeader("charset", encoding);
      post.setEntity(multipart);
      HttpResponse response = client.execute(post);
      String result = "";
      int statusCode = response.getStatusLine().getStatusCode();

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

      return result;
    } catch (Exception e) {
      Log.e("error", e.getMessage());
      return "";
    }
  }
  public static List<NameValuePair> parseForParameters(String stringResponse)
      throws JSONException, InvalidRequestException, InvalidClientException, InvalidGrantException,
          UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException,
          OAuthException {
    OAuthException exception = null;
    List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
    String[] parameters = stringResponse.split("&");
    for (String parameter : parameters) {
      if (parameter.contains("?")) {
        parameterList.add(new BasicNameValuePair("redirectUri", parameter.split("?")[0]));
        parameter = parameter.split("?")[1];
      }
      if (parameter.contains("=")) {

        String[] pair = parameter.split("=");
        BasicNameValuePair basicNameValuePair = new BasicNameValuePair(pair[0], pair[1]);
        parameterList.add(basicNameValuePair);
        if (basicNameValuePair.getName().equalsIgnoreCase("error")) {
          exception = ErrorParser.getException(basicNameValuePair.getValue());
        }
      }
    }
    if (exception != null) {
      throw exception;
    }
    return parameterList;
  }
Пример #3
0
 @Override
 public HttpURLConnection openConnection() throws MalformedURLException, IOException {
   String fullUrl = url.endsWith("?") ? url : url + "?";
   fullUrl += URLEncodedUtils.format(params, "utf-8");
   this.connection = (HttpURLConnection) new URL(fullUrl).openConnection();
   for (BasicNameValuePair header : headers) {
     connection.setRequestProperty(header.getName(), header.getValue());
   }
   return connection;
 }
Пример #4
0
 // get url voi tham so truyen len
 private static String getUrlWithParams(
     String base, String relativeUrl, List<BasicNameValuePair> params) {
   String url = getAbsoluteUrl(base, relativeUrl);
   for (int i = 0; i < params.size(); i++) {
     BasicNameValuePair b = params.get(i);
     url += "&" + b.getName() + "=" + b.getValue();
   }
   url = url.replace(" ", "%20");
   return url;
 }
 private String createRequestString(String serviceName, ArrayList<BasicNameValuePair> parameters) {
   StringBuilder sb = new StringBuilder(SERVICE_URL);
   sb.append(serviceName);
   sb.append("?");
   for (BasicNameValuePair parameter : parameters) {
     sb.append(parameter.getName());
     sb.append("=");
     sb.append(parameter.getValue());
     sb.append("&");
   }
   return sb.toString();
 }
Пример #6
0
 private String doPostForString(String url, List<BasicNameValuePair> params) {
   InputStream is = null;
   InputStreamReader in = null;
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient(); // 使用DefaultHttpClient创建HttpClient实例
     HttpPost post = new HttpPost(url); // 构建HttpPost
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 使用编码构建Post实体
     post.setEntity(entity); // 执行Post方法
     if (paramsProperty != null) {
       for (BasicNameValuePair basic : paramsProperty) {
         post.setHeader(basic.getName(), basic.getValue());
       }
     }
     HttpResponse response = httpClient.execute(post); // 获取返回实体
     is = response.getEntity().getContent();
     in = new InputStreamReader(is);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     byte[] buffer = new byte[1024];
     int lenth = 0;
     while ((lenth = is.read(buffer)) != -1) {
       bos.write(buffer, 0, lenth);
       bos.flush();
     }
     bos.close();
     String json = bos.toString();
     if (isLog) {
       LogFileHelper.getInstance().i(TAG, post.getURI().toString());
       LogFileHelper.getInstance().i(TAG, json);
     }
     return json;
   } catch (Exception e) {
     // TODO Auto-generated catch block
     LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage());
   }
   // 使用finally块来关闭输出流、输入流
   finally {
     try {
       if (is != null) {
         is.close();
       }
       if (in != null) {
         in.close();
       }
     } catch (IOException e) {
       LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage());
     }
   }
   return null;
 }
Пример #7
0
  /**
   * Creates digest-response header as defined in RFC2617.
   *
   * @param credentials User credentials
   * @param digest The response tag's value as String.
   * @return The digest-response as String.
   */
  private Header createDigestHeader(final Credentials credentials, final String digest)
      throws AuthenticationException {

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
      buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
      buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    String response = digest;
    String algorithm = getParameter("algorithm");

    String uname = credentials.getUserPrincipal().getName();

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", response));

    if (qopVariant != QOP_MISSING) {
      params.add(new BasicNameValuePair("qop", getQopVariantString()));
      params.add(new BasicNameValuePair("nc", NC));
      params.add(new BasicNameValuePair("cnonce", getCnonce()));
    }
    if (algorithm != null) {
      params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
      params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
      BasicNameValuePair param = params.get(i);
      if (i > 0) {
        buffer.append(", ");
      }
      boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
      BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
  }
Пример #8
0
  private List<BasicNameValuePair> getParamList(BasicNameValuePair... nameValuePairs) {
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    for (BasicNameValuePair obj : nameValuePairs) {
      if (obj.getValue() == null || obj.getValue().length() <= 0) continue;
      params.add(obj);
    }

    Collections.sort(
        params,
        new Comparator<BasicNameValuePair>() {

          public int compare(BasicNameValuePair lhs, BasicNameValuePair rhs) {
            return lhs.getName().compareTo(rhs.getName());
          }
        });
    return params;
  }
Пример #9
0
  /**
   * Upload weibo contents into output stream .
   *
   * @param baos : output stream for uploading weibo
   * @param params : post parameters for uploading
   * @return void
   */
  private static void paramToUpload(OutputStream baos, List<BasicNameValuePair> params) {
    BasicNameValuePair key = null;
    for (int loc = 0; loc < params.size(); loc++) {
      key = params.get(loc);
      StringBuilder temp = new StringBuilder(10);
      temp.setLength(0);
      temp.append(MP_BOUNDARY).append("\r\n");
      temp.append("content-disposition: form-data; name=\"")
          .append(key.getName())
          .append("\"\r\n\r\n");
      temp.append(key.getValue()).append("\r\n");
      byte[] res = temp.toString().getBytes();
      try {
        baos.write(res);
      } catch (IOException e) {

      }
    }
  }
Пример #10
0
  /**
   * 请求数据
   *
   * @param token 用户的token
   * @param tokenSecret 用户的tokenSecret
   * @param url 需要获取的数据url(通过url来确定需要获取的数据)
   * @param params 参数
   * @return
   */
  public HttpResponse signRequest(String token, String tokenSecret, String url, List params) {
    HttpPost post = new HttpPost(url);
    ByteArrayOutputStream bos = null;
    String file = null;
    try {
      // 参数的编码转换为utf-8
      post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

      for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair nameValuePair = (BasicNameValuePair) params.get(i);
        if (nameValuePair.getName().equals("pic")) {
          file = nameValuePair.getValue();
        }
      }

      byte[] data = null;
      bos = new ByteArrayOutputStream(1024 * 50);
      if (!TextUtils.isEmpty(file)) {
        paramToUpload(bos, params);
        // 设置表单类型和分隔符
        post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        Bitmap bf = BitmapFactory.decodeFile(file);
        imageContentToUpload(bos, bf);
        data = bos.toByteArray();
        ByteArrayEntity formEntity = new ByteArrayEntity(data);
        post.setEntity(formEntity);
      }

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    return signRequest(token, tokenSecret, post);
  }
Пример #11
0
  /**
   * Title: doGetForJson Description: 发送请求的 URL,直接返回JSON数据解析。返回集合列表 return T throws
   *
   * @param isString
   */
  private String doGetForString(String url, List<BasicNameValuePair> params) {
    InputStream is = null;
    InputStreamReader in = null;
    StringBuffer geturl = new StringBuffer();
    geturl.append(url);

    if (params != null) {
      geturl.append("?");
      for (BasicNameValuePair item : params) {
        geturl.append(item.getName() + "=" + item.getValue() + "&");
      }
      geturl.deleteCharAt(geturl.length() - 1);
    }
    try {
      URL realUrl = new URL(new String(geturl.toString().getBytes(), "ISO-8859-1"));
      // 打开和URL之间的连接
      HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
      // 设置通用的请求属性

      conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
      conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
      conn.setRequestMethod("GET");
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      if (paramsProperty != null) {
        for (BasicNameValuePair basic : paramsProperty) {
          conn.setRequestProperty(basic.getName(), basic.getValue());
        }
      }

      // 定义BufferedReader输入流来读取URL的响应
      is = conn.getInputStream();
      in = new InputStreamReader(is);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int lenth = 0;
      while ((lenth = is.read(buffer)) != -1) {
        bos.write(buffer, 0, lenth);
        bos.flush();
      }
      bos.close();
      String json = bos.toString();
      if (isLog) {
        LogFileHelper.getInstance().i(TAG, realUrl.toString());
        LogFileHelper.getInstance().i(TAG, json);
      }
      return json;
    } catch (Exception e) {

      LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage());
    }

    // 使用finally块来关闭输出流、输入流
    finally {
      try {
        if (in != null) {
          in.close();
        }
        if (is != null) {
          is.close();
        }
      } catch (IOException e) {
        LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage());
      }
    }
    return null;
  }
Пример #12
0
  /**
   * Creates digest-response header as defined in RFC2617.
   *
   * @param credentials User credentials
   * @return The digest-response as String.
   */
  private Header createDigestHeader(final Credentials credentials) throws AuthenticationException {
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    String method = getParameter("methodname");
    String algorithm = getParameter("algorithm");
    if (uri == null) {
      throw new IllegalStateException("URI may not be null");
    }
    if (realm == null) {
      throw new IllegalStateException("Realm may not be null");
    }
    if (nonce == null) {
      throw new IllegalStateException("Nonce may not be null");
    }

    // TODO: add support for QOP_INT
    int qop = QOP_UNKNOWN;
    String qoplist = getParameter("qop");
    if (qoplist != null) {
      StringTokenizer tok = new StringTokenizer(qoplist, ",");
      while (tok.hasMoreTokens()) {
        String variant = tok.nextToken().trim();
        if (variant.equals("auth")) {
          qop = QOP_AUTH;
          break;
        }
      }
    } else {
      qop = QOP_MISSING;
    }

    if (qop == QOP_UNKNOWN) {
      throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
    }

    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
      algorithm = "MD5";
    }
    // If an charset is not specified, default to ISO-8859-1.
    String charset = getParameter("charset");
    if (charset == null) {
      charset = "ISO-8859-1";
    }

    String digAlg = algorithm;
    if (digAlg.equalsIgnoreCase("MD5-sess")) {
      digAlg = "MD5";
    }

    MessageDigest digester;
    try {
      digester = createMessageDigest(digAlg);
    } catch (UnsupportedDigestAlgorithmException ex) {
      throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
    }

    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();

    if (nonce.equals(this.lastNonce)) {
      nounceCount++;
    } else {
      nounceCount = 1;
      cnonce = null;
      lastNonce = nonce;
    }
    StringBuilder sb = new StringBuilder(256);
    Formatter formatter = new Formatter(sb, Locale.US);
    formatter.format("%08x", nounceCount);
    String nc = sb.toString();

    if (cnonce == null) {
      cnonce = createCnonce();
    }

    a1 = null;
    a2 = null;
    // 3.2.2.2: Calculating digest
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
      // H( unq(username-value) ":" unq(realm-value) ":" passwd )
      //      ":" unq(nonce-value)
      //      ":" unq(cnonce-value)

      // calculated one per session
      sb.setLength(0);
      sb.append(uname).append(':').append(realm).append(':').append(pwd);
      String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
      sb.setLength(0);
      sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
      a1 = sb.toString();
    } else {
      // unq(username-value) ":" unq(realm-value) ":" passwd
      sb.setLength(0);
      sb.append(uname).append(':').append(realm).append(':').append(pwd);
      a1 = sb.toString();
    }

    String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));

    if (qop == QOP_AUTH) {
      // Method ":" digest-uri-value
      a2 = method + ':' + uri;
    } else if (qop == QOP_AUTH_INT) {
      // Method ":" digest-uri-value ":" H(entity-body)
      // TODO: calculate entity hash if entity is repeatable
      throw new AuthenticationException("qop-int method is not suppported");
    } else {
      a2 = method + ':' + uri;
    }

    String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));

    // 3.2.2.1

    String digestValue;
    if (qop == QOP_MISSING) {
      sb.setLength(0);
      sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
      digestValue = sb.toString();
    } else {
      sb.setLength(0);
      sb.append(hasha1)
          .append(':')
          .append(nonce)
          .append(':')
          .append(nc)
          .append(':')
          .append(cnonce)
          .append(':')
          .append(qop == QOP_AUTH_INT ? "auth-int" : "auth")
          .append(':')
          .append(hasha2);
      digestValue = sb.toString();
    }

    String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
      buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
      buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", digest));

    if (qop != QOP_MISSING) {
      params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
      params.add(new BasicNameValuePair("nc", nc));
      params.add(new BasicNameValuePair("cnonce", cnonce));
    }
    if (algorithm != null) {
      params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
      params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
      BasicNameValuePair param = params.get(i);
      if (i > 0) {
        buffer.append(", ");
      }
      boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
      BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
  }
  /**
   * Call the webservice using the given parameters to construct the request and return the result.
   *
   * @param context The context to use for this operation. Used to generate the user agent if
   *     needed.
   * @param urlValue The webservice URL.
   * @param method The request method to use.
   * @param parameterList The parameters to add to the request.
   * @param headerMap The headers to add to the request.
   * @param isGzipEnabled Whether the request will use gzip compression if available on the server.
   * @param userAgent The user agent to set in the request. If null, a default Android one will be
   *     created.
   * @param postText The POSTDATA text to add in the request.
   * @param credentials The credentials to use for authentication.
   * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
   * @return The result of the webservice call.
   */
  public static ConnectionResult execute(
      Context context,
      String urlValue,
      Method method,
      ArrayList<BasicNameValuePair> parameterList,
      HashMap<String, String> headerMap,
      boolean isGzipEnabled,
      String userAgent,
      String postText,
      UsernamePasswordCredentials credentials,
      boolean isSslValidationEnabled,
      File file)
      throws ConnectionException {
    HttpURLConnection connection = null;
    try {
      // Prepare the request information
      if (userAgent == null) {
        userAgent = UserAgentUtils.get(context);
      }
      if (headerMap == null) {
        headerMap = new HashMap<String, String>();
      }
      headerMap.put(HTTP.USER_AGENT, userAgent);
      if (isGzipEnabled) {
        headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
      }
      headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
      if (credentials != null) {
        headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
      }

      StringBuilder paramBuilder = new StringBuilder();
      if (parameterList != null && !parameterList.isEmpty()) {
        for (int i = 0, size = parameterList.size(); i < size; i++) {
          BasicNameValuePair parameter = parameterList.get(i);
          String name = parameter.getName();
          String value = parameter.getValue();
          if (TextUtils.isEmpty(name)) {
            // Empty parameter name. Check the next one.
            continue;
          }
          if (value == null) {
            value = "";
          }
          paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
          paramBuilder.append("=");
          paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
          paramBuilder.append("&");
        }
      }

      // Log the request
      if (DataDroidLog.canLog(Log.DEBUG)) {
        DataDroidLog.d(TAG, "Request url: " + urlValue);
        DataDroidLog.d(TAG, "Method: " + method.toString());

        if (parameterList != null && !parameterList.isEmpty()) {
          DataDroidLog.d(TAG, "Parameters:");
          for (int i = 0, size = parameterList.size(); i < size; i++) {
            BasicNameValuePair parameter = parameterList.get(i);
            String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
            DataDroidLog.d(TAG, message);
          }

          DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
        }

        if (postText != null) {
          DataDroidLog.d(TAG, "Post data: " + postText);
        }

        if (headerMap != null && !headerMap.isEmpty()) {
          DataDroidLog.d(TAG, "Headers:");
          for (Entry<String, String> header : headerMap.entrySet()) {
            DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
          }
        }
      }

      // Create the connection object
      URL url = null;
      String outputText = null;
      switch (method) {
        case GET:
        case DELETE:
          String fullUrlValue = urlValue;
          if (paramBuilder.length() > 0) {
            fullUrlValue += "?" + paramBuilder.toString();
          }
          url = new URL(fullUrlValue);
          connection = (HttpURLConnection) url.openConnection();
          break;
        case PUT:
        case POST:
          url = new URL(urlValue);
          connection = (HttpURLConnection) url.openConnection();
          connection.setDoOutput(true);

          if (paramBuilder.length() > 0) {
            outputText = paramBuilder.toString();
            headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
          } else if (postText != null) {
            outputText = postText;
          }
          break;
      }

      // Set the request method
      connection.setRequestMethod(method.toString());

      // If it's an HTTPS request and the SSL Validation is disabled
      if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
        httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
        httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
      }

      // Add the headers
      if (!headerMap.isEmpty()) {
        for (Entry<String, String> header : headerMap.entrySet()) {
          connection.addRequestProperty(header.getKey(), header.getValue());
        }
      }

      // Set the connection and read timeout
      connection.setConnectTimeout(OPERATION_TIMEOUT);
      connection.setReadTimeout(READ_OPERATION_TIMEOUT);

      // Set the outputStream content for POST and PUT requests
      if ((method == Method.POST || method == Method.PUT) && outputText != null) {
        OutputStream output = null;
        try {
          output = connection.getOutputStream();
          output.write(outputText.getBytes());
        } finally {
          if (output != null) {
            try {
              output.close();
            } catch (IOException e) {
              // Already catching the first IOException so nothing to do here.
            }
          }
        }
      }

      String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

      int responseCode = connection.getResponseCode();
      boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
      DataDroidLog.d(TAG, "Response code: " + responseCode);

      if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
        String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
        throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
      }

      InputStream errorStream = connection.getErrorStream();
      if (errorStream != null) {
        throw new ConnectionException("error", responseCode);
      }

      String body = convertStreamToString(connection.getInputStream(), isGzip, file, context);

      if (DataDroidLog.canLog(Log.VERBOSE)) {
        DataDroidLog.v(TAG, "Response body: ");

        int pos = 0;
        int bodyLength = body.length();
        while (pos < bodyLength) {
          DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
          pos = pos + 200;
        }
      }

      return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
      DataDroidLog.e(TAG, "IOException", e);
      throw new ConnectionException(e);
    } catch (KeyManagementException e) {
      DataDroidLog.e(TAG, "KeyManagementException", e);
      throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
      DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
      throw new ConnectionException(e);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }