사용자를 만들고 서버에 사용자 이름과 암호를 POST하려고합니다. 아래의 코드는 일반 Java 파일에서 정상적으로 실행되지만안드로이드 네트워크 AsyncTask
android.os.NetworkOnMainThreadException 때문에 Android에서 실행할 때 다운됩니다.
검색을 수행하고 AsyncTask를 사용하도록 지시 받았지만 AsyncTask를 사용하는 방법, 매개 변수를 실행하고 전달하는 방법을 알지 못합니다. url과 account Info를 전달해야합니다. 둘 다 String입니다.
다음은 일반 자바 파일에서 실행되는 코드입니다.
public String sendPost(String accountInfo, String input_url) throws Exception {
// Establish Connection
URL url = new URL(input_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// Post account info to server
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(accountInfo);
wr.flush();
wr.close();
// Check response code and message
int responseCode = con.getResponseCode();
IntputStream is = con.getErrorStream();
String contentAsString = CovertToString(is, 500);
JSONObject jObject = new JSONObject(contentAsString);
jObject.put("response", responseCode);
return jObject;
}
다음은 AsyncTask로 만들려고 시도한 것입니다.
class Test extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... params) {
try {
// Establish Connection
URL url = new URL(input_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// Post account info to server
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(accountInfo);
wr.flush();
wr.close();
// Check response code and message
int responseCode = con.getResponseCode();
IntputStream is = con.getErrorStream();
String contentAsString = CovertToString(is, 500);
JSONObject jObject = new JSONObject(contentAsString);
jObject.put("response", responseCode);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
메서드를 호출하고 매개 변수를 전달하는 방법을 모르거나 메서드를 올바르게 구현했는지 확실하지 않습니다.
미리 감사드립니다. 감사합니다.