android

[Android] HttpUrlConnection 사용하기

포카리s 2016. 2. 24. 19:43
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
1
2
3
4
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class HttpUrlConnection {
 
    public String performPostCall(String requestUrl, HashMap<StringString> postDataParams){
        URL url;
        String respones = "";
 
        try{
            url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
 
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
 
            if(responseCode == HttpURLConnection.HTTP_OK){
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 
                while ((line = br.readLine()) != null){
                    respones += line;
                }
            }else{
                respones = "";
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        Log.e("TEST""ResPonse > "+respones);
        return respones;
    }
 
    private String getPostDataString(HashMap<StringString> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<StringString> entry : params.entrySet()){
            if(first)
                first = false;
            else
                result.append("&");
 
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        Log.e("TEST""In Params > "+result.toString());
        return result.toString();
    }
 
}
 
cs