기본 콘텐츠로 건너뛰기

Android, HttpURLConnection

*** implementation


new Thread(new Runnable() {
public void run() {
    HashMap params = new HashMap();      
    params.put("param1", "1");
    HttpURLConnection connection = null;      
    try {
        URL url = new URL("http://xxxxx.com/api/xxxx");           

        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Accept", "application/json");
        connection = ConnectionManager.setParams(connection, params);
            connection.connect();
            Integer responseCode  = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

            activity.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    //refresh GUI
                }
                    });
            }
        }catch(Exception e){
        e.printStackTrace();  
    }finally{
            if(connection != null){
                    connection.disconnect();      
        }

        }
}
}).start();




*** set Parameter



public static HttpURLConnection setParams(HttpURLConnection conn,
            HashMap<String, String> params) throws Exception{

    Uri.Builder builder = new Uri.Builder();

    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));   
    }
    String query = builder.build().getEncodedQuery();
    OutputStream os = conn.getOutputStream();

    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));

    writer.write(query);   
    writer.flush();
    writer.close();
    os.close();   
    return conn;

}



댓글

이 블로그의 인기 게시물

Android, 서명이 충돌하는 같은 이름의 기존 패키지가 이미 설치되어 있습니다.

Nexus 7 1세대 4.4 Kitkat 앱이 설치되지 않습니다. 서명이 충돌하는 같은 이름의 기존 패키지가 이미 설치되어 있습니다. 위의 증상으로 apk로 앱이 설치되지 않음. 설치되어있는 앱을 지우고 다시 설치하려고 해도 되지 않음. 구글 플레이에서 설치할때도 비활성->활성되는듯 설치 딜레이가 없었음. 앱을 삭제할시 해당사용자에서 링크만 삭제되는 듯이 보임. 어플리케이션 리스트의 가장밑에 설치하려는 앱의 아이콘을 발견.(삭제됨이라고 표시) 그 앱의 메뉴를 열어 "모든 사용자에서 삭제"를 선택하면 앱의 아이콘이 사라진다. 그후 apk를 설치하면 정상으로 진행.