Когда я запускаю свою программу, показывающую его ошибки E/HTTP Client: Ошибка в httpconnectionandroid.os.NetworkOnMainThreadExceptionОтправка запроса JSON POST из Android ошибки приема E/HTTP Client: Ошибка в HTTP connectionandroid.os.NetworkOnMainThreadException
Это простая программа входа с именем пользователя и паролем. Когда я нажимаю кнопку входа в систему, он должен удалять сервер методом POST в json-синтаксическом анализе и возвращать ответ с успехом или неудачей.
Я новичок в разработке Android. Найдите мою ошибку здесь и объясните, почему она не работает.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "";
static EditText username, password;
Button login;
String Name, Pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
login = (Button) findViewById(R.id.button);
login.setOnClickListener(this);
}
public String excutePost() throws IOException {
String url = "website.com/login";
URL u = new URL(url);
HttpURLConnection connection = null;
try{
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("POST");
//set the sending type and receiving type to json
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Host", "website.com");
connection.setAllowUserInteraction(false);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
String uname = username.getText().toString();
String pword = password.getText().toString();
JSONObject jsonParam = new JSONObject();
jsonParam.put("userName", uname);
jsonParam.put("password", pword);
DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
printout.writeBytes(jsonParam.toString());
printout.flush();
printout.close();
//Connect to the server
connection.connect();
int status = connection.getResponseCode();
Log.i("HTTP Client", "HTTP status code : " + status);
switch (status) {
case 200:
case 201:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
bufferedReader.close();
Log.i("HTTP Client", "Received String : " + sb.toString());
//return received string
return sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("HTTP Client", "Error in http connection" + ex.toString());
} catch (IOException ex) {
Log.e("HTTP Client", "Error in http connection" + ex.toString());
} catch (Exception ex) {
Log.e("HTTP Client", "Error in http connection" + ex.toString());
} finally {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception ex) {
Log.e("HTTP Client", "Error in http connection" + ex.toString());
}
}
}
return "";
}
@Override
public void onClick(View v) {
try {
excutePost();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Просьба помочь мне решить эту проблему.
Prajapti вставлен в файл AndroidManifest.xml. Какой код я могу использовать внутри этого прогона(). Просьба указать, из какой строки на какую строку? –
paul
try { excutePost(); } catch (IOException e) { e.printStackTrace(); } –