*** 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;
}
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;
}
댓글
댓글 쓰기