HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key", "value"); // post로 넘길 값을 맵에 담아 넘김
HttpCon httpCon = new HttpCon(url, hashMap);
try {
String result = httpCon.execute().get();
Log.e(TAG, "result -- > " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
public class HttpCon extends AsyncTask<Void, Void, String> {
private static final String TAG = "HttpCon";
String url = "";
HashMap<String, String> hash = new HashMap<>();
public HttpCon(String _url, HashMap<String, String> _hash){
url = _url;
hash = _hash;
}
@Override
protected String doInBackground(Void... voids) {
URL Url;
String result = "";
try {
Url = new URL(url); // URL화 한다.
HttpURLConnection conn = (HttpURLConnection) Url.openConnection(); // URL을 연결한 객체 생성.
conn.setRequestMethod("POST"); // get방식 통신
conn.setDoOutput(true); // 쓰기모드 지정
conn.setDoInput(true); // 읽기모드 지정
conn.setUseCaches(false); // 캐싱데이터를 받을지 안받을지
conn.setDefaultUseCaches(false); // 캐싱데이터 디폴트 값 설정
OutputStream os = conn.getOutputStream(); // 서버로 보내기 위한 출력 스트림
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // UTF-8로 전송
bw.write(getPostString(hash)); // 매개변수 전송
bw.flush();
bw.close();
os.close();
InputStream is = conn.getInputStream(); //데이타를 받기위 구멍을 열어준다
StringBuilder builder = new StringBuilder(); //문자열을 담기 위한 객체
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); //문자열 셋 세팅
String line;
while ((line = reader.readLine()) != null) {
builder.append(line+ "\n");
}
result = builder.toString();
// Log.e(TAG, "result -- > " + result);
conn.disconnect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPreExecute(){
super.onPreExecute();
}
private String getPostString(HashMap<String, String> map) {
StringBuilder result = new StringBuilder();
boolean first = true; // 첫 번째 매개변수 여부
for (Map.Entry<String, String> entry : map.entrySet()) {
if (first)
first = false;
else // 첫 번째 매개변수가 아닌 경우엔 앞에 &를 붙임
result.append("&");
try { // UTF-8로 주소에 키와 값을 붙임
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException ue) {
ue.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return result.toString();
}
}