├── .gitignore ├── RESTclient-example ├── res │ ├── drawable-hdpi │ │ └── icon.png │ ├── drawable-ldpi │ │ └── icon.png │ ├── drawable-mdpi │ │ └── icon.png │ ├── values │ │ └── strings.xml │ └── layout │ │ └── main.xml ├── lib │ └── CWAC-WakefulIntentService.jar ├── default.properties ├── src │ └── com │ │ └── tylersmith │ │ ├── webservice │ │ ├── receiver │ │ │ ├── WebReceiver.java │ │ │ └── BootReceiver.java │ │ ├── service │ │ │ └── WebService.java │ │ └── ui │ │ │ └── Main.java │ │ └── restclient │ │ ├── RequestMethod.java │ │ └── RestClient.java ├── AndroidManifest.xml └── proguard.cfg ├── RESTclient └── src │ └── com │ └── tylersmith │ └── net │ ├── RequestMethod.java │ └── RestClient.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .classpath 3 | .project 4 | .settings 5 | bin 6 | gen 7 | -------------------------------------------------------------------------------- /RESTclient-example/res/drawable-hdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyvsmith/RESTclient-Android/HEAD/RESTclient-example/res/drawable-hdpi/icon.png -------------------------------------------------------------------------------- /RESTclient-example/res/drawable-ldpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyvsmith/RESTclient-Android/HEAD/RESTclient-example/res/drawable-ldpi/icon.png -------------------------------------------------------------------------------- /RESTclient-example/res/drawable-mdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyvsmith/RESTclient-Android/HEAD/RESTclient-example/res/drawable-mdpi/icon.png -------------------------------------------------------------------------------- /RESTclient-example/lib/CWAC-WakefulIntentService.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyvsmith/RESTclient-Android/HEAD/RESTclient-example/lib/CWAC-WakefulIntentService.jar -------------------------------------------------------------------------------- /RESTclient-example/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebServiceExample 4 | 5 | -------------------------------------------------------------------------------- /RESTclient-example/res/layout/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | -------------------------------------------------------------------------------- /RESTclient-example/default.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system use, 7 | # "build.properties", and override values to adapt the script to your 8 | # project structure. 9 | 10 | # Project target. 11 | target=android-10 12 | -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/webservice/receiver/WebReceiver.java: -------------------------------------------------------------------------------- 1 | package com.tylersmith.webservice.receiver; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | 7 | import com.commonsware.cwac.wakeful.WakefulIntentService; 8 | import com.tylersmith.webservice.service.WebService; 9 | 10 | 11 | public class WebReceiver extends BroadcastReceiver { 12 | @Override 13 | public void onReceive(Context context, Intent intent) { 14 | WakefulIntentService.sendWakefulWork(context, WebService.class); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RESTclient/src/com/tylersmith/net/RequestMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Tyler Smith. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.tylersmith.net; 18 | 19 | public enum RequestMethod { 20 | DELETE, GET, POST, PUT 21 | } -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/restclient/RequestMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Tyler Smith. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.tylersmith.restclient; 18 | 19 | public enum RequestMethod { 20 | DELETE, GET, POST, PUT 21 | } -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/webservice/receiver/BootReceiver.java: -------------------------------------------------------------------------------- 1 | package com.tylersmith.webservice.receiver; 2 | 3 | import android.app.AlarmManager; 4 | import android.app.PendingIntent; 5 | import android.content.BroadcastReceiver; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.os.SystemClock; 9 | 10 | public class BootReceiver extends BroadcastReceiver { 11 | 12 | @Override 13 | public void onReceive(Context context, Intent intent) { 14 | AlarmManager mgr = (AlarmManager) context 15 | .getSystemService(Context.ALARM_SERVICE); 16 | Intent service = new Intent(context, WebReceiver.class); 17 | PendingIntent pi = PendingIntent.getBroadcast(context, 0, service, 0); 18 | 19 | //Updates once every two hours 20 | mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 21 | SystemClock.elapsedRealtime(), 1000*60*60*2, pi); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /RESTclient-example/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RESTclient-Android 2 | This library is designed to greatly assist consuming RESTful webservices. Originally I started by using the library listed in the contributions. I then modified to DRY up the script, added PUT and DELETE verbs, HTTP basic authentication, and a JSON body. 3 | 4 | ## Usage 5 | The code below is an example using a GET request to grab JSON from the server 6 | 7 | RestClient client = new RestClient(webServiceUrl); 8 | client.addBasicAuthentication(username, password); 9 | try { 10 | client.execute(RequestMethod.GET); 11 | if (client.getResponseCode() != 200) { 12 | //return server error 13 | return client.getErrorMessage(); 14 | } 15 | //return valid data 16 | JSONObject jObj = new JSONObject(client.getResponse()); 17 | return jObj.toString(); 18 | } catch(Exception e) { 19 | return e.toString(); 20 | } 21 | 22 | ## Contributions 23 | http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/ 24 | 25 | 26 | ##RESTclient-Example 27 | This example uses a service to consume a webservice in the background and update the activity if its in use, or store the data for the next time the user is active. 28 | 29 | 30 | ## License 31 | Release under the Apache 2 license. -------------------------------------------------------------------------------- /RESTclient-example/proguard.cfg: -------------------------------------------------------------------------------- 1 | -optimizationpasses 5 2 | -dontusemixedcaseclassnames 3 | -dontskipnonpubliclibraryclasses 4 | -dontpreverify 5 | -verbose 6 | -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* 7 | 8 | -keep public class * extends android.app.Activity 9 | -keep public class * extends android.app.Application 10 | -keep public class * extends android.app.Service 11 | -keep public class * extends android.content.BroadcastReceiver 12 | -keep public class * extends android.content.ContentProvider 13 | -keep public class * extends android.app.backup.BackupAgentHelper 14 | -keep public class * extends android.preference.Preference 15 | -keep public class com.android.vending.licensing.ILicensingService 16 | 17 | -keepclasseswithmembernames class * { 18 | native ; 19 | } 20 | 21 | -keepclasseswithmembernames class * { 22 | public (android.content.Context, android.util.AttributeSet); 23 | } 24 | 25 | -keepclasseswithmembernames class * { 26 | public (android.content.Context, android.util.AttributeSet, int); 27 | } 28 | 29 | -keepclassmembers enum * { 30 | public static **[] values(); 31 | public static ** valueOf(java.lang.String); 32 | } 33 | 34 | -keep class * implements android.os.Parcelable { 35 | public static final android.os.Parcelable$Creator *; 36 | } 37 | -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/webservice/service/WebService.java: -------------------------------------------------------------------------------- 1 | package com.tylersmith.webservice.service; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONObject; 5 | 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.content.SharedPreferences; 9 | import android.os.Binder; 10 | import android.os.Handler; 11 | import android.os.IBinder; 12 | import android.preference.PreferenceManager; 13 | 14 | import com.commonsware.cwac.wakeful.WakefulIntentService; 15 | import com.tylersmith.restclient.RequestMethod; 16 | import com.tylersmith.restclient.RestClient; 17 | import com.tylersmith.webservice.ui.Main; 18 | 19 | 20 | public class WebService extends WakefulIntentService implements Runnable { 21 | 22 | public static final String EXTRAS_RESPONSE_MESSAGE = "tylersmith.webservice.response_message"; 23 | public static final String EXTRAS_SUCCESS = "tylersmith.webservice.success"; 24 | 25 | public static final String WEB_INTENT_FILTER = "tylersmith.webservice.intent.filter"; 26 | private final IBinder binder = new WebBinder(); 27 | 28 | private Handler handler = new Handler(); 29 | protected Context context; 30 | 31 | 32 | public WebService() { 33 | super("UpdateService"); 34 | } 35 | 36 | @Override 37 | protected void doWakefulWork(Intent intent) { 38 | context = getApplicationContext(); 39 | //preventing this from running unless specifically called from within the activity or through the alarm manager 40 | if(!intent.getBooleanExtra("fromApplication", false)) 41 | new Thread(this).start(); 42 | } 43 | 44 | @Override 45 | public void run() { 46 | String twitterUrl = "http://search.twitter.com/search.json"; 47 | RestClient client = new RestClient(twitterUrl); 48 | client.addParam("q", "android"); 49 | try { 50 | client.execute(RequestMethod.GET); 51 | if(client.getResponseCode() == 200) { 52 | //Successfully connected 53 | JSONObject jObj = new JSONObject(client.getResponse()); 54 | JSONArray jResults = jObj.getJSONArray("results"); 55 | 56 | SharedPreferences.Editor editPrefs = 57 | PreferenceManager.getDefaultSharedPreferences(context).edit(); 58 | editPrefs.putString(Main.PREFS_DATA, jResults.toString()); 59 | editPrefs.commit(); 60 | broadCast(true, "Success"); 61 | 62 | } else { 63 | //error connecting to server, lets just return an error 64 | broadCast(false, "Error Connecting"); 65 | } 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } 69 | 70 | 71 | } 72 | 73 | private void broadCast(boolean success, String message) { 74 | Intent intent = new Intent(); 75 | intent.putExtra(EXTRAS_SUCCESS, success); 76 | intent.putExtra(EXTRAS_RESPONSE_MESSAGE, message); 77 | intent.setAction(WEB_INTENT_FILTER); 78 | sendBroadcast(intent); 79 | } 80 | 81 | @Override 82 | public void onCreate() { 83 | super.onCreate(); 84 | context = getApplicationContext(); 85 | } 86 | 87 | @Override 88 | public IBinder onBind(Intent intent) { 89 | return binder; 90 | } 91 | 92 | public class WebBinder extends Binder { 93 | public WebService getService() { 94 | return WebService.this; 95 | } 96 | } 97 | 98 | @Override 99 | public void onDestroy() { 100 | super.onDestroy(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/webservice/ui/Main.java: -------------------------------------------------------------------------------- 1 | package com.tylersmith.webservice.ui; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.json.JSONArray; 6 | 7 | import android.app.AlertDialog; 8 | import android.app.ListActivity; 9 | import android.app.ProgressDialog; 10 | import android.content.BroadcastReceiver; 11 | import android.content.ComponentName; 12 | import android.content.Context; 13 | import android.content.DialogInterface; 14 | import android.content.Intent; 15 | import android.content.IntentFilter; 16 | import android.content.ServiceConnection; 17 | import android.content.SharedPreferences; 18 | import android.os.Bundle; 19 | import android.os.IBinder; 20 | import android.preference.PreferenceManager; 21 | import android.view.Menu; 22 | import android.view.MenuItem; 23 | import android.widget.ArrayAdapter; 24 | 25 | import com.commonsware.cwac.wakeful.WakefulIntentService; 26 | import com.tylersmith.webservice.R; 27 | import com.tylersmith.webservice.service.WebService; 28 | 29 | public class Main extends ListActivity { 30 | 31 | private Main activity; 32 | private WebService webService; 33 | ProgressDialog dialog; 34 | ArrayList data; 35 | public final static String PREFS_NAME = "tylersmith.webservice"; 36 | public final static String PREFS_DATA = "data"; 37 | 38 | private final int MENU_REFRESH = 0; 39 | 40 | @Override 41 | public void onCreate(Bundle savedInstanceState) { 42 | activity = this; 43 | super.onCreate(savedInstanceState); 44 | setContentView(R.layout.main); 45 | 46 | bindService(); 47 | bindList(); 48 | 49 | } 50 | 51 | @Override 52 | protected void onResume() { 53 | super.onResume(); 54 | 55 | } 56 | 57 | private void bindService() { 58 | Intent service = new Intent(this, WebService.class); 59 | service.putExtra("fromApplication", true); 60 | // need to use this instead of startService(); 61 | WakefulIntentService.sendWakefulWork(getApplicationContext(), service); 62 | // Binding ..this block can also start service if not started already 63 | Intent bindIntent = new Intent(this, WebService.class); 64 | bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE); 65 | // Register Broadcast Receiver 66 | IntentFilter filter = new IntentFilter(WebService.WEB_INTENT_FILTER); 67 | registerReceiver(myReceiver, filter); 68 | } 69 | 70 | private void bindList() { 71 | try { 72 | loadData(); 73 | } catch (Exception e) { 74 | e.printStackTrace(); 75 | } 76 | 77 | ArrayAdapter adapter = new ArrayAdapter(this, 78 | android.R.layout.simple_list_item_1, data); 79 | adapter.setNotifyOnChange(true); 80 | setListAdapter(adapter); 81 | } 82 | 83 | // Using JSON since it serializes so nicely 84 | // Could also create a custom adapter extended from BaseAdapter but thats 85 | // outside the scope of this tutorial. 86 | private void loadData() throws Exception { 87 | SharedPreferences sp = PreferenceManager 88 | .getDefaultSharedPreferences(this); 89 | JSONArray jData = new JSONArray(sp.getString(PREFS_DATA, "[]")); 90 | 91 | data = new ArrayList(); 92 | for (int index = 0; index < jData.length(); index++) { 93 | data.add(jData.getJSONObject(index).getString("from_user") 94 | + jData.getJSONObject(index).getString("text")); 95 | } 96 | } 97 | 98 | private void refreshData() { 99 | if (dialog == null || !dialog.isShowing()) 100 | dialog = ProgressDialog.show(Main.this, "", 101 | "Loading. Please wait...", true); 102 | new Thread(webService).start(); 103 | } 104 | 105 | private BroadcastReceiver myReceiver = new BroadcastReceiver() { 106 | 107 | @Override 108 | public void onReceive(Context context, Intent intent) { 109 | 110 | Bundle extras = intent.getExtras(); 111 | 112 | boolean success = extras.getBoolean(WebService.EXTRAS_SUCCESS, 113 | false); 114 | String message = extras 115 | .getString(WebService.EXTRAS_RESPONSE_MESSAGE); 116 | 117 | if (message == null) 118 | message = "There was a connection problem, please try again later"; 119 | 120 | if (success) { 121 | try { 122 | loadData(); 123 | } catch (Exception e) { 124 | e.printStackTrace(); 125 | } 126 | } else { 127 | //Using a reference to the activity instead of getApplicationContext() to prevent breaking 128 | //This may keep a reference to the original and cause a memory leak 129 | //TODO: investigate further 130 | AlertDialog.Builder builder = new AlertDialog.Builder(activity); 131 | builder.setMessage(message) 132 | .setCancelable(false) 133 | .setNeutralButton("Ok", 134 | new DialogInterface.OnClickListener() { 135 | @Override 136 | public void onClick(DialogInterface dialog, 137 | int id) { 138 | dialog.cancel(); 139 | } 140 | }); 141 | 142 | final AlertDialog alert = builder.create(); 143 | } 144 | if (dialog != null && dialog.isShowing()) 145 | dialog.dismiss(); 146 | } 147 | }; 148 | 149 | private ServiceConnection serviceConnection = new ServiceConnection() { 150 | @Override 151 | public void onServiceConnected(ComponentName name, IBinder service) { 152 | webService = ((WebService.WebBinder) service).getService(); 153 | } 154 | 155 | @Override 156 | public void onServiceDisconnected(ComponentName name) { 157 | webService = null; 158 | } 159 | }; 160 | 161 | @Override 162 | public boolean onPrepareOptionsMenu(Menu menu) { 163 | menu.clear(); 164 | menu.add(0, MENU_REFRESH, 0, "Refresh").setIcon( 165 | android.R.drawable.ic_menu_rotate); 166 | return true; 167 | }; 168 | 169 | @Override 170 | public boolean onOptionsItemSelected(MenuItem item) { 171 | switch (item.getItemId()) { 172 | case MENU_REFRESH: { 173 | refreshData(); 174 | } 175 | } 176 | return super.onOptionsItemSelected(item); 177 | } 178 | 179 | @Override 180 | public void onDestroy() { 181 | super.onDestroy(); 182 | // Unregister the Broadcast receiver and unbind service 183 | unregisterReceiver(myReceiver); 184 | unbindService(serviceConnection); 185 | } 186 | 187 | } -------------------------------------------------------------------------------- /RESTclient/src/com/tylersmith/net/RestClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Tyler Smith. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.tylersmith.net; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.net.URLEncoder; 24 | import java.util.ArrayList; 25 | 26 | import org.apache.http.HttpEntity; 27 | import org.apache.http.HttpResponse; 28 | import org.apache.http.NameValuePair; 29 | import org.apache.http.auth.UsernamePasswordCredentials; 30 | import org.apache.http.client.ClientProtocolException; 31 | import org.apache.http.client.entity.UrlEncodedFormEntity; 32 | import org.apache.http.client.methods.HttpDelete; 33 | import org.apache.http.client.methods.HttpGet; 34 | import org.apache.http.client.methods.HttpPost; 35 | import org.apache.http.client.methods.HttpPut; 36 | import org.apache.http.client.methods.HttpUriRequest; 37 | import org.apache.http.entity.StringEntity; 38 | import org.apache.http.impl.auth.BasicScheme; 39 | import org.apache.http.impl.client.DefaultHttpClient; 40 | import org.apache.http.message.BasicNameValuePair; 41 | import org.apache.http.params.HttpConnectionParams; 42 | import org.apache.http.params.HttpParams; 43 | import org.apache.http.protocol.HTTP; 44 | 45 | 46 | import android.content.Context; 47 | 48 | public class RestClient { 49 | 50 | private boolean authentication; 51 | private ArrayList headers; 52 | 53 | private String jsonBody; 54 | private String message; 55 | 56 | private ArrayList params; 57 | private String response; 58 | private int responseCode; 59 | 60 | private String url; 61 | 62 | // HTTP Basic Authentication 63 | private String username; 64 | private String password; 65 | 66 | protected Context context; 67 | 68 | public RestClient(String url) { 69 | this.url = url; 70 | params = new ArrayList(); 71 | headers = new ArrayList(); 72 | } 73 | //Be warned that this is sent in clear text, don't use basic auth unless you have to. 74 | public void addBasicAuthentication(String user, String pass) { 75 | authentication = true; 76 | username = user; 77 | password = pass; 78 | } 79 | 80 | public void addHeader(String name, String value) { 81 | headers.add(new BasicNameValuePair(name, value)); 82 | } 83 | 84 | public void addParam(String name, String value) { 85 | params.add(new BasicNameValuePair(name, value)); 86 | } 87 | 88 | public void execute(RequestMethod method) 89 | throws Exception { 90 | switch (method) { 91 | case GET: { 92 | HttpGet request = new HttpGet(url + addGetParams()); 93 | request = (HttpGet) addHeaderParams(request); 94 | executeRequest(request, url); 95 | break; 96 | } 97 | case POST: { 98 | HttpPost request = new HttpPost(url); 99 | request = (HttpPost) addHeaderParams(request); 100 | request = (HttpPost) addBodyParams(request); 101 | executeRequest(request, url); 102 | break; 103 | } 104 | case PUT: { 105 | HttpPut request = new HttpPut(url); 106 | request = (HttpPut) addHeaderParams(request); 107 | request = (HttpPut) addBodyParams(request); 108 | executeRequest(request, url); 109 | break; 110 | } 111 | case DELETE: { 112 | HttpDelete request = new HttpDelete(url); 113 | request = (HttpDelete) addHeaderParams(request); 114 | executeRequest(request, url); 115 | } 116 | } 117 | } 118 | 119 | private HttpUriRequest addHeaderParams(HttpUriRequest request) 120 | throws Exception { 121 | for (NameValuePair h : headers) { 122 | request.addHeader(h.getName(), h.getValue()); 123 | } 124 | 125 | if (authentication) { 126 | 127 | UsernamePasswordCredentials creds = new UsernamePasswordCredentials( 128 | username, password); 129 | request.addHeader(new BasicScheme().authenticate(creds, request)); 130 | } 131 | 132 | return request; 133 | } 134 | 135 | private HttpUriRequest addBodyParams(HttpUriRequest request) 136 | throws Exception { 137 | if (jsonBody != null) { 138 | request.addHeader("Content-Type", "application/json"); 139 | if (request instanceof HttpPost) 140 | ((HttpPost) request).setEntity(new StringEntity(jsonBody, 141 | "UTF-8")); 142 | else if (request instanceof HttpPut) 143 | ((HttpPut) request).setEntity(new StringEntity(jsonBody, 144 | "UTF-8")); 145 | 146 | } else if (!params.isEmpty()) { 147 | if (request instanceof HttpPost) 148 | ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, 149 | HTTP.UTF_8)); 150 | else if (request instanceof HttpPut) 151 | ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params, 152 | HTTP.UTF_8)); 153 | } 154 | return request; 155 | } 156 | 157 | private String addGetParams() 158 | throws Exception { 159 | StringBuffer combinedParams = new StringBuffer(); 160 | if (!params.isEmpty()) { 161 | combinedParams.append("?"); 162 | for (NameValuePair p : params) { 163 | combinedParams.append((combinedParams.length() > 1 ? "&" : "") 164 | + p.getName() + "=" 165 | + URLEncoder.encode(p.getValue(), "UTF-8")); 166 | } 167 | } 168 | return combinedParams.toString(); 169 | } 170 | 171 | public String getErrorMessage() { 172 | return message; 173 | } 174 | 175 | public String getResponse() { 176 | return response; 177 | } 178 | 179 | public int getResponseCode() { 180 | return responseCode; 181 | } 182 | 183 | public void setContext(Context ctx) { 184 | context = ctx; 185 | } 186 | 187 | public void setJSONString(String data) { 188 | jsonBody = data; 189 | } 190 | 191 | private void executeRequest(HttpUriRequest request, String url) { 192 | 193 | DefaultHttpClient client = new DefaultHttpClient(); 194 | HttpParams params = client.getParams(); 195 | 196 | // Setting 30 second timeouts 197 | HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); 198 | HttpConnectionParams.setSoTimeout(params, 30 * 1000); 199 | 200 | HttpResponse httpResponse; 201 | 202 | try { 203 | httpResponse = client.execute(request); 204 | responseCode = httpResponse.getStatusLine().getStatusCode(); 205 | message = httpResponse.getStatusLine().getReasonPhrase(); 206 | 207 | HttpEntity entity = httpResponse.getEntity(); 208 | 209 | if (entity != null) { 210 | 211 | InputStream instream = entity.getContent(); 212 | response = convertStreamToString(instream); 213 | 214 | // Closing the input stream will trigger connection release 215 | instream.close(); 216 | } 217 | 218 | } catch (ClientProtocolException e) { 219 | client.getConnectionManager().shutdown(); 220 | e.printStackTrace(); 221 | } catch (IOException e) { 222 | client.getConnectionManager().shutdown(); 223 | e.printStackTrace(); 224 | } 225 | } 226 | 227 | private static String convertStreamToString(InputStream is) { 228 | 229 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 230 | StringBuilder sb = new StringBuilder(); 231 | 232 | String line = null; 233 | try { 234 | while ((line = reader.readLine()) != null) { 235 | sb.append(line + "\n"); 236 | } 237 | } catch (IOException e) { 238 | e.printStackTrace(); 239 | } finally { 240 | try { 241 | is.close(); 242 | } catch (IOException e) { 243 | e.printStackTrace(); 244 | } 245 | } 246 | return sb.toString(); 247 | } 248 | } -------------------------------------------------------------------------------- /RESTclient-example/src/com/tylersmith/restclient/RestClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Tyler Smith. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.tylersmith.restclient; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.net.URLEncoder; 24 | import java.util.ArrayList; 25 | 26 | import org.apache.http.HttpEntity; 27 | import org.apache.http.HttpResponse; 28 | import org.apache.http.NameValuePair; 29 | import org.apache.http.auth.UsernamePasswordCredentials; 30 | import org.apache.http.client.ClientProtocolException; 31 | import org.apache.http.client.entity.UrlEncodedFormEntity; 32 | import org.apache.http.client.methods.HttpDelete; 33 | import org.apache.http.client.methods.HttpGet; 34 | import org.apache.http.client.methods.HttpPost; 35 | import org.apache.http.client.methods.HttpPut; 36 | import org.apache.http.client.methods.HttpUriRequest; 37 | import org.apache.http.entity.StringEntity; 38 | import org.apache.http.impl.auth.BasicScheme; 39 | import org.apache.http.impl.client.DefaultHttpClient; 40 | import org.apache.http.message.BasicNameValuePair; 41 | import org.apache.http.params.HttpConnectionParams; 42 | import org.apache.http.params.HttpParams; 43 | import org.apache.http.protocol.HTTP; 44 | 45 | 46 | import android.content.Context; 47 | 48 | public class RestClient { 49 | 50 | private boolean authentication; 51 | private ArrayList headers; 52 | 53 | private String jsonBody; 54 | private String message; 55 | 56 | private ArrayList params; 57 | private String response; 58 | private int responseCode; 59 | 60 | private String url; 61 | 62 | // HTTP Basic Authentication 63 | private String username; 64 | private String password; 65 | 66 | protected Context context; 67 | 68 | public RestClient(String url) { 69 | this.url = url; 70 | params = new ArrayList(); 71 | headers = new ArrayList(); 72 | } 73 | //Be warned that this is sent in clear text, don't use basic auth unless you have to. 74 | public void addBasicAuthentication(String user, String pass) { 75 | authentication = true; 76 | username = user; 77 | password = pass; 78 | } 79 | 80 | public void addHeader(String name, String value) { 81 | headers.add(new BasicNameValuePair(name, value)); 82 | } 83 | 84 | public void addParam(String name, String value) { 85 | params.add(new BasicNameValuePair(name, value)); 86 | } 87 | 88 | public void execute(RequestMethod method) throws Exception { 89 | switch (method) { 90 | case GET: { 91 | HttpGet request = new HttpGet(url + addGetParams()); 92 | request = (HttpGet) addHeaderParams(request); 93 | executeRequest(request, url); 94 | break; 95 | } 96 | case POST: { 97 | HttpPost request = new HttpPost(url); 98 | request = (HttpPost) addHeaderParams(request); 99 | request = (HttpPost) addBodyParams(request); 100 | executeRequest(request, url); 101 | break; 102 | } 103 | case PUT: { 104 | HttpPut request = new HttpPut(url); 105 | request = (HttpPut) addHeaderParams(request); 106 | request = (HttpPut) addBodyParams(request); 107 | executeRequest(request, url); 108 | break; 109 | } 110 | case DELETE: { 111 | HttpDelete request = new HttpDelete(url); 112 | request = (HttpDelete) addHeaderParams(request); 113 | executeRequest(request, url); 114 | } 115 | } 116 | } 117 | 118 | private HttpUriRequest addHeaderParams(HttpUriRequest request) 119 | throws Exception { 120 | for (NameValuePair h : headers) { 121 | request.addHeader(h.getName(), h.getValue()); 122 | } 123 | 124 | if (authentication) { 125 | 126 | UsernamePasswordCredentials creds = new UsernamePasswordCredentials( 127 | username, password); 128 | request.addHeader(new BasicScheme().authenticate(creds, request)); 129 | } 130 | 131 | return request; 132 | } 133 | 134 | private HttpUriRequest addBodyParams(HttpUriRequest request) 135 | throws Exception { 136 | if (jsonBody != null) { 137 | request.addHeader("Content-Type", "application/json"); 138 | if (request instanceof HttpPost) 139 | ((HttpPost) request).setEntity(new StringEntity(jsonBody, 140 | "UTF-8")); 141 | else if (request instanceof HttpPut) 142 | ((HttpPut) request).setEntity(new StringEntity(jsonBody, 143 | "UTF-8")); 144 | 145 | } else if (!params.isEmpty()) { 146 | if (request instanceof HttpPost) 147 | ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, 148 | HTTP.UTF_8)); 149 | else if (request instanceof HttpPut) 150 | ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params, 151 | HTTP.UTF_8)); 152 | } 153 | return request; 154 | } 155 | 156 | private String addGetParams() throws Exception { 157 | //Using StringBuffer append for better performance. 158 | StringBuffer combinedParams = new StringBuffer(); 159 | if (!params.isEmpty()) { 160 | combinedParams.append("?"); 161 | for (NameValuePair p : params) { 162 | combinedParams.append((combinedParams.length() > 1 ? "&" : "") 163 | + p.getName() + "=" 164 | + URLEncoder.encode(p.getValue(), "UTF-8")); 165 | } 166 | } 167 | return combinedParams.toString(); 168 | } 169 | 170 | public String getErrorMessage() { 171 | return message; 172 | } 173 | 174 | public String getResponse() { 175 | return response; 176 | } 177 | 178 | public int getResponseCode() { 179 | return responseCode; 180 | } 181 | 182 | public void setContext(Context ctx) { 183 | context = ctx; 184 | } 185 | 186 | public void setJSONString(String data) { 187 | jsonBody = data; 188 | } 189 | 190 | private void executeRequest(HttpUriRequest request, String url) { 191 | 192 | DefaultHttpClient client = new DefaultHttpClient(); 193 | HttpParams params = client.getParams(); 194 | 195 | // Setting 30 second timeouts 196 | HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); 197 | HttpConnectionParams.setSoTimeout(params, 30 * 1000); 198 | 199 | HttpResponse httpResponse; 200 | 201 | try { 202 | httpResponse = client.execute(request); 203 | responseCode = httpResponse.getStatusLine().getStatusCode(); 204 | message = httpResponse.getStatusLine().getReasonPhrase(); 205 | 206 | HttpEntity entity = httpResponse.getEntity(); 207 | 208 | if (entity != null) { 209 | 210 | InputStream instream = entity.getContent(); 211 | response = convertStreamToString(instream); 212 | 213 | // Closing the input stream will trigger connection release 214 | instream.close(); 215 | } 216 | 217 | } catch (ClientProtocolException e) { 218 | client.getConnectionManager().shutdown(); 219 | e.printStackTrace(); 220 | } catch (IOException e) { 221 | client.getConnectionManager().shutdown(); 222 | e.printStackTrace(); 223 | } 224 | } 225 | 226 | private static String convertStreamToString(InputStream is) { 227 | 228 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 229 | StringBuilder sb = new StringBuilder(); 230 | 231 | String line = null; 232 | try { 233 | while ((line = reader.readLine()) != null) { 234 | sb.append(line + "\n"); 235 | } 236 | } catch (IOException e) { 237 | e.printStackTrace(); 238 | } finally { 239 | try { 240 | is.close(); 241 | } catch (IOException e) { 242 | e.printStackTrace(); 243 | } 244 | } 245 | return sb.toString(); 246 | } 247 | } --------------------------------------------------------------------------------