Http Get and Http Post : Http Connection « Network « Android






Http Get and Http Post

    
//package com.helloandroid.acashboard.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class ApiHelper {

  SharedPreferences preferences;
  static String username;
  static String apiKey;

  public ApiHelper(Context context) {
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    username = preferences.getString("editTextName", "helloandroid"); // ezek
                                      // valtoznak
    apiKey = preferences.getString("editTextPsw",
        "gifnta5hc04cur9pqvu4mhg7i7te60nuh42c8n0vz927o7nuaa"); // ezek
                                    // valtoznak
  }

  /**
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public String httpGet(String method) throws ClientProtocolException,
      IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(method);

    /* headers */
    httpget.setHeader("Accept", "application/xml");
    httpget.setHeader("Content-Type", "application/xml");

    /* authentication */
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
        username + ":" + apiKey);
    httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        credentials);

    /* execute */
    BasicHttpResponse httpResponse = null;
    httpResponse = (BasicHttpResponse) httpclient.execute(httpget);
    /* return response */
    return TextHelper.GetText(httpResponse);
  }

  /**
   * @param method
   *            - example: "https://api.cashboardapp.com/projects"
   * @param data
   *            - example:
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  public String httpPost(String method, String data)
      throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(method);

    /* headers */
    httppost.setHeader("Accept", "application/xml");
    httppost.setHeader("Content-Type", "application/xml");

    /* authentication */
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
        username + ":" + apiKey);
    httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
        credentials);

    StringEntity se = new StringEntity(data, HTTP.UTF_8);
    se.setContentType("text/xml");
    httppost.setEntity(se);

    /* execute */
    BasicHttpResponse httpResponse = null;
    httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
    /* return response */
    return TextHelper.GetText(httpResponse);
  }

}

class TextHelper {
  public static String GetText(InputStream in) {
    String text = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      text = sb.toString();
    } catch (Exception ex) {

    } finally {
      try {

        in.close();
      } catch (Exception ex) {
      }
    }
    return text;
  }

  public static String GetText(HttpResponse response) {
    String text = "";
    try {
      text = GetText(response.getEntity().getContent());
    } catch (Exception ex) {
    }
    return text;
  }
}

   
    
    
    
  








Related examples in the same category

1.Http Connection
2.Using HttpGet to get the web response
3.Create Http connection
4.Http connection with
5.HttpGet and DefaultHttpClient
6.Http Post
7.Simple HTTP Request
8.Http Request Class
9.Get Text from HttpResponse
10.Http Request
11.Http Downloader
12.Is Http Url Available
13.Http Retriever
14.Receive Response from HttpURLConnection
15.Print http headers. Useful for debugging.
16.Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/
17.Send message with HttpPost
18.Get Http Stream
19.Generic Object Http Loader
20.Http Get and DefaultHttpClient
21.Gets http output from URL
22.Util for Http Get
23.do Http Get Request and return the status code
24.Http Get
25.implements HttpClient
26.Get File From HTTP
27.Make all redirects to go to http in stead of https
28.New Http Client Manager
29.Http Client Manager
30.Multipart Post
31.Get Server Data
32.Yahoo News Crawler
33.Send Packet
34.Read a web page
35.parse Request Header
36.Data Send Utils
37.This class is in charge of synchronizing the events (with due dates) with Google Calendar
38.Update Favicon
39.Converts key-value pair to appropriate signature for Facebook.