public class Main2Activity extends AppCompatActivity {
Authorization mt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
helloTextView = (EditText)findViewById(R.id.editText);
}
public void onClick(View view) {
mt = new Authorization();
mt.execute();
}
class Authorization extends AsyncTask<Void, Void, Void> {
String resultString = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
String myURL = "http://site.ru";
String parammetrs = "login=1&password=2";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Length", "" + Integer.toString(parammetrs.getBytes().length));
OutputStream os = conn.getOutputStream();
data = parammetrs.getBytes("UTF-8");
os.write(data);
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
}
} catch (IOException e) {
//resultString = "IOException:" + e.getMessage();
} catch (Exception e) {
//resultString = "Exception:" + e.getMessage();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Toast toast = Toast.makeText(getApplicationContext(), resultString, Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
Нашел на тостере ответ, очень долго тупил и юзал в потоке активити, т.к. не сразу догадался что нужно было использовать
AsyncTask.