Restful Client : Restful « Network « Android






Restful Client

   
//package com.herochen.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

class RestClient {
  private static final String TAG = "CareClient-RestClient";
  public static final String server = "http://174.140.165.237";
  //public static final String server = "http://192.168.1.101:8080";
  private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
  
  public static JSONObject get(String url, Map<String,String> params){
    
    HttpClient httpClient = new DefaultHttpClient();
    // Prepare a request object
    if(params != null){
      int i = 0;
      for(Map.Entry<String, String> param : params.entrySet()){
        if(i == 0){
          url += "?";
        } else {
          url += "&";
        }
        
        try {
          url += param.getKey()+"="+URLEncoder.encode(param.getValue(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
          Log.e(TAG, e.getMessage());
        }
        i++;
      }
    }
    
    HttpGet httpGet = new HttpGet(url); 
    // Execute the request
    HttpResponse response = null;
    JSONObject json = null;
    try {

      //???????????GET???????????????????
      response = httpClient.execute(httpGet);
      Log.i("GET status code:",response.getStatusLine().toString());
      // Get hold of the response entity
      HttpEntity entityResp = response.getEntity();
      
      if (entityResp != null) {
        // A Simple JSON Response Read
        InputStream instream = entityResp.getContent();
        String result = convertStreamToString(instream);
        // A Simple JSONObject Creation
        json = new JSONObject(result);
        // Closing the input stream will trigger connection release
        instream.close();
      }

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return json;
  }
  
  public static JSONObject post(String url, HttpEntity entityReq){
    
    HttpClient httpClient = new DefaultHttpClient();
    // Prepare a request object
    HttpPost httpPost = new HttpPost(url); 
    // Execute the request
    HttpResponse response = null;
    JSONObject json = null;
    try {
      httpPost.setEntity(entityReq);
      //httpPost.setHeader(name, value);

      //???????????POST???????????????????
      response = httpClient.execute(httpPost);
      Log.i("POST status code:",response.getStatusLine().toString());
      // Get hold of the response entity
      HttpEntity entityResp = response.getEntity();
      
      if (entityResp != null) {
        // A Simple JSON Response Read
        InputStream instream = entityResp.getContent();
        String result = convertStreamToString(instream);
        // A Simple JSONObject Creation
        json = new JSONObject(result);
        // Closing the input stream will trigger connection release
        instream.close();
      }

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return json;
  }
  
  public static JSONObject put(String url, HttpEntity entityReq){
    
    HttpClient httpClient = new DefaultHttpClient();
    // Prepare a request object
    HttpPut httpPut = new HttpPut(url); 
    // Execute the request
    HttpResponse response = null;
    JSONObject json = null;
    try {
      httpPut.setEntity(entityReq);
      //httpPost.setHeader(name, value);

      //???????????PUT???????????????????
      response = httpClient.execute(httpPut);
      Log.i("PUT status code:",response.getStatusLine().toString());
      // Get hold of the response entity
      HttpEntity entityResp = response.getEntity();
      
      if (entityResp != null) {
        // A Simple JSON Response Read
        InputStream instream = entityResp.getContent();
        String result = convertStreamToString(instream);
        // A Simple JSONObject Creation
        json = new JSONObject(result);
        // Closing the input stream will trigger connection release
        instream.close();
      }

    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return json;
  }
}

   
    
    
  








Related examples in the same category

1.Restful authentication task
2.Rest Client