]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/gss-lib-2.2/src/com/pras/conn/HttpConHandler.java
Added gss-lib-2.2.
[Dictionary.git] / jars / gss-lib-2.2 / src / com / pras / conn / HttpConHandler.java
1 /*\r
2  * Copyright (C) 2010 Prasanta Paul, http://prasanta-paul.blogspot.com\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.pras.conn;\r
18 \r
19 import java.io.BufferedReader;\r
20 import java.io.InputStream;\r
21 import java.io.InputStreamReader;\r
22 import java.io.OutputStream;\r
23 import java.net.HttpURLConnection;\r
24 import java.net.URL;\r
25 import java.net.URLEncoder;\r
26 import java.util.HashMap;\r
27 import java.util.Iterator;\r
28 \r
29 import com.pras.Log;\r
30 \r
31 /**\r
32  * HTTP Connection handler, supports GET, POST, PUT and DELETE.\r
33  * \r
34  * @author Prasanta Paul\r
35  */\r
36 public class HttpConHandler {\r
37         \r
38         /*\r
39          * HTTP Headers\r
40          */\r
41         public static final String AUTHORIZATION_HTTP_HEADER = "Authorization";\r
42         public static final String GDATA_VERSION_HTTP_HEADER = "GData-Version";\r
43         public static final String CONTENT_LENGTH_HTTP_HEADER = "Content-Length";\r
44         public static final String CONTENT_TYPE_HTTP_HEADER = "Content-Type";\r
45         \r
46         public static final int HTTP_GET = 0xA1;\r
47         public static final int HTTP_POST = 0xA2;\r
48         public static final int HTTP_DELETE = 0xA3;\r
49         public static final int HTTP_PUT = 0xA4;\r
50         \r
51         /**\r
52          * @param urlStr HTTP URL\r
53          * @param type Type of Connection (POST, GET, PUT or DELETE)\r
54          * @param httpHeaders HTTP headers\r
55          * @param postData Data to be sent as a part of POST/PUT request\r
56          * \r
57          * @return ATOM XML feed and Response/Error message\r
58          */\r
59         public Response doConnect(String urlStr, int type, HashMap<String, String> httpHeaders, String postData) {\r
60                 \r
61                 String res = null;\r
62                 HttpURLConnection con = null;\r
63                 Response response = new Response();\r
64                 String TAG = "HttpConHandler";\r
65 \r
66                 try{\r
67                         /*\r
68                          * IMPORTANT: \r
69                          * User SHOULD provide URL Encoded Parms\r
70                          */\r
71                         Log.p(TAG, "URL="+ urlStr);\r
72                         // TODO: Remove proxy\r
73                         // Somehow Eclipse is not detecting Proxy\r
74                         // HTTP Proxy\r
75                         System.getProperties().put("http.proxyHost", "168.219.61.250");\r
76                         System.getProperties().put("http.proxyPort", "8080");\r
77                         // HTTPS Proxy\r
78                         System.getProperties().put("https.proxyHost", "168.219.61.252");\r
79                         System.getProperties().put("https.proxyPort", "8080");\r
80                         URL url = new URL(urlStr);\r
81                         con = (HttpURLConnection) url.openConnection();\r
82                         \r
83                         //con.setInstanceFollowRedirects(false);\r
84                         \r
85                         OutputStream out = null;\r
86                         \r
87                         // Set headers\r
88                         /*\r
89                          * All subsequent request to Google Spreadsheet/Data API\r
90                          * should include following 2 Headers\r
91                          */\r
92                         //con.setRequestProperty("Authorization", "GoogleLogin auth="+ authToken);\r
93                         //con.setRequestProperty("GData-Version", "3.0");\r
94                         \r
95                         if(httpHeaders != null){\r
96                                 //System.out.println("Number of HTTP Headers: "+ httpHeaders.size());\r
97                                 Iterator<String> keys = httpHeaders.keySet().iterator();\r
98                                 while(keys.hasNext()){\r
99                                         String k = keys.next();\r
100                                         con.setRequestProperty(k, httpHeaders.get(k));\r
101                                 }\r
102                         }\r
103                         \r
104                         if(type == HTTP_POST){\r
105                                 con.setDoOutput(true);\r
106                                 out = con.getOutputStream();\r
107                                 out.write(postData.getBytes());\r
108                                 out.flush();\r
109                         }\r
110                         else if(type == HTTP_GET){\r
111                                 con.setDoInput(true);\r
112                         }\r
113                         else if(type == HTTP_DELETE){\r
114                                 con.setRequestMethod("DELETE");\r
115                                 con.connect();\r
116                         }\r
117                         else if(type == HTTP_PUT){\r
118                                 con.setRequestMethod("PUT");\r
119                                 // Send Data\r
120                                 con.setDoOutput(true);\r
121                                 out = con.getOutputStream();\r
122                                 out.write(postData.getBytes());\r
123                                 out.flush();\r
124                         }\r
125                         \r
126                         // Read Response Code\r
127                         response.setResponseCode(""+ con.getResponseCode());\r
128                         response.setResponseMessage(con.getResponseMessage());\r
129                         \r
130                         // Read InputStream\r
131                         BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));\r
132                         StringBuffer strBuf = new StringBuffer();\r
133                         String line = "";\r
134                         while((line = reader.readLine()) != null)\r
135                                 strBuf.append(line);\r
136                         \r
137                         reader.close();\r
138                         \r
139                         if(out != null)\r
140                                 out.close();\r
141                         \r
142                         res = strBuf.toString();\r
143                         \r
144                         response.setOutput(res);\r
145                         \r
146                         Log.p(TAG, "Response from Google Server: \n"+ res);\r
147                         \r
148                 }catch(Exception ex){\r
149                         \r
150                         Log.p(TAG, "Error in connection: "+ ex.toString());\r
151                         // Oops Exception\r
152                         response.setError(true);\r
153                         \r
154                         // Set Exception\r
155                         response.setException(ex);\r
156                         \r
157                         if(con == null)\r
158                                 return response; \r
159                         \r
160                         InputStream error_in = con.getErrorStream();\r
161                         \r
162                         if(error_in == null)\r
163                                 return response;\r
164                         \r
165                         // Read the error stream\r
166                         BufferedReader reader = new BufferedReader(new InputStreamReader(error_in));\r
167                         if(reader == null)\r
168                                 return response;\r
169                         \r
170                         StringBuffer errStrBuf = new StringBuffer();\r
171                         String line = "";\r
172                         \r
173                         try{\r
174                                 while((line = reader.readLine()) != null)\r
175                                         errStrBuf.append(line);\r
176                         \r
177                                 // Set Error Stream Message\r
178                                 response.setErrorStreamMsg(errStrBuf.toString());\r
179                         \r
180                                 reader.close();\r
181                         \r
182                                 // Display error on logging console\r
183                                 response.printErrorLog();\r
184                         \r
185                         }catch(Exception e){\r
186                                 Log.p(TAG, "Error in reading Stream: "+ e.getMessage());\r
187                         }\r
188                 }\r
189                 return response;\r
190         }\r
191         \r
192         /**\r
193          * Encode URL parameters in UTF-8 format\r
194          * \r
195          * @param str String to be URL encoded\r
196          * \r
197          * @return\r
198          */\r
199         public static String encode(String str){\r
200                 try{\r
201                         str = URLEncoder.encode(str, "UTF-8");\r
202                 }catch(Exception ex){ex.printStackTrace();}\r
203                 return str;\r
204         }\r
205 }\r