This tutorial is focused on creating a very simple HTTP client for Google's mobile operating system Android, which then can communicate with a web server and exchange JSON information. I won't go too much into detail, since the code is pretty much self-explaining and already has a lot of comments describing the program flow.
1) Create a new Android project
2) Add permission to access the Internet from your application to your AndroidManifest.xml
<MANIFEST>
2
3 <USES-PERMISSION android:name="android.permission.INTERNET">
4 </USES-PERMISSION>
5 </MANIFEST>
3) Create a new (static) class called HttpClient.java
package com.devstream.http;
016 import java.io.BufferedReader;
017 import java.io.IOException;
018 import java.io.InputStream;
019 import java.io.InputStreamReader;
020 import java.util.zip.GZIPInputStream;
021 import org.apache.http.Header;
022 import org.apache.http.HttpEntity;
023 import org.apache.http.HttpResponse;
024 import org.apache.http.client.methods.HttpPost;
025 import org.apache.http.entity.StringEntity;
026 import org.apache.http.impl.client.DefaultHttpClient;
027 import org.json.JSONObject;
028 import android.util.Log;
029 public class HttpClient {
030 private static final String TAG = "HttpClient";
031 public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
032 try {
033 DefaultHttpClient httpclient = new DefaultHttpClient();
034 HttpPost httpPostRequest = new HttpPost(URL);
035 StringEntity se;
036 se = new StringEntity(jsonObjSend.toString());
037 // Set HTTP parameters
038 httpPostRequest.setEntity(se);
039 httpPostRequest.setHeader("Accept", "application/json");
040 httpPostRequest.setHeader("Content-type", "application/json");
041 httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
042 long t = System.currentTimeMillis();
043 HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
044 Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
045 // Get hold of the response entity (-> the data):
046 HttpEntity entity = response.getEntity();
047 if (entity != null) {
048 // Read the content stream
049 InputStream instream = entity.getContent();
050 Header contentEncoding = response.getFirstHeader("Content-Encoding");
051 if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
052 instream = new GZIPInputStream(instream);
053 }
054 // convert content stream to a String
055 String resultString= convertStreamToString(instream);
056 instream.close();
057 resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
058 // Transform the String into a JSONObject
059 JSONObject jsonObjRecv = new JSONObject(resultString);
060 // Raw DEBUG output of our received JSON object:
061 Log.i(TAG,"<jsonobject>\n"+jsonObjRecv.toString()+"\n</jsonobject>");
062 return jsonObjRecv;
063 }
064 }
065 catch (Exception e)
066 {
067 // More about HTTP exception handling in another tutorial.
068 // For now we just print the stack trace.
069 e.printStackTrace();
070 }
071 return null;
072 }
073 private static String convertStreamToString(InputStream is) {
074 /*
075 * To convert the InputStream to String we use the BufferedReader.readLine()
076 * method. We iterate until the BufferedReader return null which means
077 * there's no more data to read. Each line will appended to a StringBuilder
078 * and returned as String.
079 *
080 * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
081 */
082 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
083 StringBuilder sb = new StringBuilder();
084 String line = null;
085 try {
086 while ((line = reader.readLine()) != null) {
087 sb.append(line + "\n");
088 }
089 } catch (IOException e) {
090 e.printStackTrace();
091 } finally {
092 try {
093 is.close();
094 } catch (IOException e) {
095 e.printStackTrace();
096 }
097 }
098 return sb.toString();
099 }
}
4) Add the following code to your MainActivity.java
package com.devstream.http;
17 import org.json.JSONException;
18 import org.json.JSONObject;
19 import android.app.Activity;
20 import android.os.Bundle;
21 import android.util.Log;
22 public class MainActivity extends Activity {
23 private static final String TAG = "MainActivity";
24 private static final String URL = "http://www.yourdomain.com:80";
25 @Override
26 public void onCreate(Bundle savedInstanceState) {
27 super.onCreate(savedInstanceState);
28 setContentView(R.layout.main);
29 // JSON object to hold the information, which is sent to the server
30 JSONObject jsonObjSend = new JSONObject();
31 try {
32 // Add key/value pairs
33 jsonObjSend.put("key_1", "value_1");
34 jsonObjSend.put("key_2", "value_2");
35 // Add a nested JSONObject (e.g. for header information)
36 JSONObject header = new JSONObject();
37 header.put("deviceType","Android"); // Device type
38 header.put("deviceVersion","2.0"); // Device OS version
39 header.put("language", "es-es"); // Language of the Android client
40 jsonObjSend.put("header", header);
41
42 // Output the JSON object we're sending to Logcat:
43 Log.i(TAG, jsonObjSend.toString(2));
44 } catch (JSONException e) {
45 e.printStackTrace();
46 }
47 // Send the HttpPostRequest and receive a JSONObject in return
48 JSONObject jsonObjRecv = HttpClient.SendHttpPost(URL, jsonObjSend);
49 /*
50 * From here on do whatever you want with your JSONObject, e.g.
51 * 1) Get the value for a key: jsonObjRecv.get("key");
52 * 2) Get a nested JSONObject: jsonObjRecv.getJSONObject("key")
53 * 3) Get a nested JSONArray: jsonObjRecv.getJSONArray("key")
54 */
55 }
}
No comments:
Post a Comment