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:
01 | public class WeatherHttpClient { |
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/" ; |
06 | public String getWeatherData(String location) { |
07 | HttpURLConnection con = null ; |
08 | InputStream is = null ; |
11 | con = (HttpURLConnection) ( new URL(BASE_URL + location)).openConnection(); |
12 | con.setRequestMethod( "GET" ); |
14 | con.setDoOutput( true ); |
18 | StringBuffer buffer = new StringBuffer(); |
19 | is = con.getInputStream(); |
20 | BufferedReader br = new BufferedReader( new InputStreamReader(is)); |
22 | while ( (line = br.readLine()) != null ) |
23 | buffer.append(line + "\r\n" ); |
27 | return buffer.toString(); |
33 | try { is.close(); } catch (Throwable t) {} |
34 | try { con.disconnect(); } catch (Throwable t) {} |
41 | public byte [] getImage(String code) { |
42 | HttpURLConnection con = null ; |
43 | InputStream is = null ; |
45 | con = (HttpURLConnection) ( new URL(IMG_URL + code)).openConnection(); |
46 | con.setRequestMethod( "GET" ); |
48 | con.setDoOutput( true ); |
52 | is = con.getInputStream(); |
53 | byte [] buffer = new byte [ 1024 ]; |
54 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
56 | while ( is.read(buffer) != - 1 ) |
59 | return baos.toByteArray(); |
65 | try { is.close(); } catch (Throwable t) {} |
66 | try { con.disconnect(); } catch (Throwable t) {} |
No comments:
Post a Comment