Search in sources :

Example 6 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project Android by hmkcode.

the class MainActivity method POST.

public static String POST(String url, Person person) {
    InputStream inputStream = null;
    String result = "";
    try {
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", person.getName());
        jsonObject.accumulate("country", person.getCountry());
        jsonObject.accumulate("twitter", person.getTwitter());
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 
        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);
        // 6. set httpPost Entity
        httpPost.setEntity(se);
        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        // 10. convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    // 11. return result
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException)

Example 7 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project rainbow by juankysoriano.

the class RainbowIO method createInputRaw.

/**
     * Call createInput() without automatic gzip decompression.
     */
public static InputStream createInputRaw(Context context, final String filename) {
    InputStream stream = null;
    if (filename == null) {
        return null;
    }
    if (filename.length() == 0) {
        return null;
    }
    if (filename.indexOf(":") != -1) {
        // at least smells like URL
        try {
            HttpGet httpRequest = null;
            httpRequest = new HttpGet(URI.create(filename));
            final HttpClient httpclient = new DefaultHttpClient();
            final HttpResponse response = httpclient.execute(httpRequest);
            final HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (final MalformedURLException mfue) {
        } catch (final FileNotFoundException fnfe) {
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    // Try the assets folder
    final AssetManager assets = context.getAssets();
    try {
        stream = assets.open(filename);
        if (stream != null) {
            return stream;
        }
    } catch (final IOException e) {
    }
    // Maybe this is an absolute path, didja ever think of that?
    final File absFile = new File(filename);
    if (absFile.exists()) {
        try {
            stream = new FileInputStream(absFile);
            if (stream != null) {
                return stream;
            }
        } catch (final FileNotFoundException fnfe) {
        // fnfe.printStackTrace();
        }
    }
    // Maybe this is a file that was written by the sketch later.
    final File sketchFile = new File(sketchPath(context, filename));
    if (sketchFile.exists()) {
        try {
            stream = new FileInputStream(sketchFile);
            if (stream != null) {
                return stream;
            }
        } catch (final FileNotFoundException fnfe) {
        }
    }
    // Attempt to load the file more directly. Doesn't like paths.
    try {
        stream = context.openFileInput(filename);
        if (stream != null) {
            return stream;
        }
    } catch (final FileNotFoundException e) {
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) AssetManager(android.content.res.AssetManager) HttpEntity(org.apache.http.HttpEntity) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) FileInputStream(java.io.FileInputStream)

Example 8 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project c-geo by just-radovan.

the class cgDirectionImg method getDrawable.

public void getDrawable(String geocode, String code) {
    String dirName;
    String fileName;
    if (geocode == null || geocode.length() == 0 || code == null || code.length() == 0) {
        return;
    }
    if (geocode != null && geocode.length() > 0) {
        dirName = settings.getStorage() + geocode + "/";
        fileName = settings.getStorage() + geocode + "/direction.png";
    } else {
        return;
    }
    File dir = null;
    dir = new File(settings.getStorage());
    if (dir.exists() == false) {
        dir.mkdirs();
    }
    dir = new File(dirName);
    if (dir.exists() == false) {
        dir.mkdirs();
    }
    dir = null;
    HttpClient client = null;
    HttpGet getMethod = null;
    HttpResponse httpResponse = null;
    HttpEntity entity = null;
    BufferedHttpEntity bufferedEntity = null;
    boolean ok = false;
    for (int i = 0; i < 3; i++) {
        if (i > 0)
            Log.w(cgSettings.tag, "cgDirectionImg.getDrawable: Failed to download data, retrying. Attempt #" + (i + 1));
        try {
            client = new DefaultHttpClient();
            getMethod = new HttpGet("http://www.geocaching.com/ImgGen/seek/CacheDir.ashx?k=" + code);
            httpResponse = client.execute(getMethod);
            entity = httpResponse.getEntity();
            bufferedEntity = new BufferedHttpEntity(entity);
            Log.i(cgSettings.tag, "[" + entity.getContentLength() + "B] Downloading direction image " + code);
            if (bufferedEntity != null) {
                InputStream is = (InputStream) bufferedEntity.getContent();
                FileOutputStream fos = new FileOutputStream(fileName);
                try {
                    byte[] buffer = new byte[4096];
                    int l;
                    while ((l = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, l);
                    }
                    ok = true;
                } catch (IOException e) {
                    Log.e(cgSettings.tag, "cgDirectionImg.getDrawable (saving to cache): " + e.toString());
                } finally {
                    is.close();
                    fos.flush();
                    fos.close();
                }
            }
            if (ok == true) {
                break;
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgDirectionImg.getDrawable (downloading from web): " + e.toString());
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 9 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project pinot by linkedin.

the class BackfillControllerAPIs method getAllSegments.

/**
   * Fetches the list of all segment names for a table
   * @param tableName
   * @return
   * @throws IOException
   */
public List<String> getAllSegments(String tableName) throws IOException {
    List<String> allSegments = new ArrayList<>();
    HttpClient controllerClient = new DefaultHttpClient();
    HttpGet req = new HttpGet(SEGMENTS_ENDPOINT + URLEncoder.encode(tableName, UTF_8));
    HttpResponse res = controllerClient.execute(controllerHttpHost, req);
    try {
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new IllegalStateException(res.getStatusLine().toString());
        }
        InputStream content = res.getEntity().getContent();
        String response = IOUtils.toString(content);
        List<String> allSegmentsPaths = getSegmentsFromResponse(response);
        for (String segment : allSegmentsPaths) {
            allSegments.add(segment.substring(segment.lastIndexOf("/") + 1));
        }
        LOGGER.info("All segments : {}", allSegments);
    } finally {
        if (res.getEntity() != null) {
            EntityUtils.consume(res.getEntity());
        }
    }
    return allSegments;
}
Also used : InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 10 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project pinot by linkedin.

the class BackfillControllerAPIs method getSegmentMetadata.

/**
   * Returns the metadata of a segment, given the segment name and table name
   * @param tableName - table where segment resides
   * @param segmentName - name of the segment
   * @return
   * @throws IOException
   */
public Map<String, String> getSegmentMetadata(String tableName, String segmentName) throws IOException {
    Map<String, String> metadata = null;
    HttpClient controllerClient = new DefaultHttpClient();
    HttpGet req = new HttpGet(TABLES_ENDPOINT + URLEncoder.encode(tableName, UTF_8) + "/" + SEGMENTS_ENDPOINT + URLEncoder.encode(segmentName, UTF_8) + "/" + METADATA_ENDPOINT);
    HttpResponse res = controllerClient.execute(controllerHttpHost, req);
    try {
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new IllegalStateException(res.getStatusLine().toString());
        }
        InputStream content = res.getEntity().getContent();
        String metadataResponse = IOUtils.toString(content);
        metadata = getMetadataFromResponse(metadataResponse);
    } finally {
        if (res.getEntity() != null) {
            EntityUtils.consume(res.getEntity());
        }
    }
    return metadata;
}
Also used : InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)481 HttpResponse (org.apache.http.HttpResponse)293 HttpGet (org.apache.http.client.methods.HttpGet)227 HttpClient (org.apache.http.client.HttpClient)203 IOException (java.io.IOException)158 HttpPost (org.apache.http.client.methods.HttpPost)107 Test (org.junit.Test)86 HttpEntity (org.apache.http.HttpEntity)84 ClientProtocolException (org.apache.http.client.ClientProtocolException)64 InputStream (java.io.InputStream)60 Scheme (org.apache.http.conn.scheme.Scheme)53 BasicHttpParams (org.apache.http.params.BasicHttpParams)51 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)49 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)48 HttpParams (org.apache.http.params.HttpParams)47 ArrayList (java.util.ArrayList)45 URI (java.net.URI)43 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)38 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)38 InputStreamReader (java.io.InputStreamReader)37