Sunday, December 15, 2013

HTTP Request and Response

HTTP Request and Response

Now we have to exchange information with the remote server using HTTP protocol. We have to send information and then read the response. We covered this topic in the previous post( Android HTTP Client: GET, POST, Download, Upload, Multipart Request) so we won’t describe it again, we simply show the code:
view sourceprint?
01public class WeatherHttpClient {
02 
03    private static String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q=";
04    private static String IMG_URL = "http://openweathermap.org/img/w/";
05 
06    public String getWeatherData(String location) {
07        HttpURLConnection con = null ;
08        InputStream is = null;
09 
10        try {
11            con = (HttpURLConnection) ( new URL(BASE_URL + location)).openConnection();
12            con.setRequestMethod("GET");
13            con.setDoInput(true);
14            con.setDoOutput(true);
15            con.connect();
16 
17            // Let's read the response
18            StringBuffer buffer = new StringBuffer();
19            is = con.getInputStream();
20            BufferedReader br = new BufferedReader(new InputStreamReader(is));
21            String line = null;
22            while (  (line = br.readLine()) != null )
23                buffer.append(line + "\r\n");
24 
25            is.close();
26            con.disconnect();
27            return buffer.toString();
28        }
29        catch(Throwable t) {
30            t.printStackTrace();
31        }
32        finally {
33            try { is.close(); } catch(Throwable t) {}
34            try { con.disconnect(); } catch(Throwable t) {}
35        }
36 
37        return null;
38 
39    }
40 
41    public byte[] getImage(String code) {
42        HttpURLConnection con = null ;
43        InputStream is = null;
44        try {
45            con = (HttpURLConnection) ( new URL(IMG_URL + code)).openConnection();
46            con.setRequestMethod("GET");
47            con.setDoInput(true);
48            con.setDoOutput(true);
49            con.connect();
50 
51            // Let's read the response
52            is = con.getInputStream();
53            byte[] buffer = new byte[1024];
54            ByteArrayOutputStream baos = new ByteArrayOutputStream();
55 
56            while ( is.read(buffer) != -1)
57                baos.write(buffer);
58 
59            return baos.toByteArray();
60        }
61        catch(Throwable t) {
62            t.printStackTrace();
63        }
64        finally {
65            try { is.close(); } catch(Throwable t) {}
66            try { con.disconnect(); } catch(Throwable t) {}
67        }
68 
69        return null;
70 
71    }
72}

No comments:

Post a Comment