#java #android #faq
Здравствуйте. Пытаюсь сделать POST запрос на ajax страницу с помощью HttpURLConnection. Сильно не пинайте, я только сегодня начал практиковать Java и Android. Тестю на API 22 (Intel x86). В обычном хроме та же страница нормально загружается. Logcat: 03-24 10:23:26.842 4679-4679/? I/art: Late-enabling -Xcheck:jni 03-24 10:23:27.402 4679-4679/com.gobonus.gobonus D/AndroidRuntime: Shutting down VM 03-24 10:23:27.427 4679-4679/com.gobonus.gobonus E/AndroidRuntime: FATAL EXCEPTION: main Process: com.gobonus.gobonus, PID: 4679 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gobonus.gobonus/com.gobonus.gobonus.WelcomeActivity}: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110) at libcore.io.IoBridge.connectErrno(IoBridge.java:137) at libcore.io.IoBridge.connect(IoBridge.java:122) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456) at java.net.Socket.connect(Socket.java:882) at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174) at com.android.okhttp.Connection.connect(Connection.java:152) at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276) at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211) at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382) at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106) at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217) at com.gobonus.gobonus.Request.(Request.java:65) at com.gobonus.gobonus.WelcomeActivity.onCreate(WelcomeActivity.java:15) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 03-24 10:23:27.498 4679-4690/com.gobonus.gobonus W/art: Suspending all threads took: 26.757ms Request.java: package com.gobonus.gobonus; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class Request { private final String USER_AGENT = "GoBonus Android Client 1.0"; private final String API_SERVER = "http://192.168.2.21"; public String Content; public Request (String session_token, String uri, String params) { String urlParameters = "session_token="+session_token+"&"+params; // url params byte[] postData = new byte[0]; System.setProperty("http.agent", USER_AGENT); // user agent truck // api = android.os.Build.VERSION_CODES.KITKAT) { postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); } else postData = urlParameters.getBytes(Charset.forName("UTF-8")); int postDataLength = postData.length; URL url = null; try { url = new URL( API_SERVER + uri); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection conn= null; try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); try { conn.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try { DataOutputStream wr = new DataOutputStream( conn.getOutputStream()); wr.write( postData ); conn.connect(); Content = ConvertData(conn); } catch (IOException e) { e.printStackTrace(); } } protected String ConvertData (HttpURLConnection url) throws IOException { // local variables String line; StringBuffer text = new StringBuffer(); InputStreamReader in = new InputStreamReader((InputStream) url.getContent()); BufferedReader buff = new BufferedReader(in); do { line = buff.readLine(); text.append(line + "\n"); } while (line != null); return text.toString(); } } WelcomeActivity.java package com.gobonus.gobonus; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class WelcomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView WebTest = (TextView) findViewById(R.id.webTest); WebTest.setText(new Request("123", "/ajax", "foo=bar").Content); setContentView(R.layout.activity_welcome); } public void LoginGo(View view) { Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class); startActivity(intent); } } Манифест Layout
Ответы
Ответ 1
Эксепшн NetworkOnMainThreadException говорит о том, что вы используете сетевые запросы в главном потоке, используйте AsyncTask для запуска запроса в отдельном от UI потока. И Метод setContentView, нужно вызывать до того, как будете обращаться к элементам разметки. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); TextView WebTest = (TextView) findViewById(R.id.webTest); WebTest.setText(new Request("123", "/ajax", "foo=bar").Content); } UPD Пример запроса через AsyncTask. Метод doInBackground выполняется в отдельном от UI потоке, после того, как вы выполнили запрос и получили ответ, ваши данные упадут в onPostExecute, который выполняется уже в потоке UI. Не обращайтесь к потоку UI в doInBackground, вызовет Exception. public class WelcomeActivity extends AppCompatActivity { TextView WebTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); WebTest = (TextView) findViewById(R.id.webTest); new AsyncRequest().execute("123", "/ajax", "foo=bar"); } class AsyncRequest extends AsyncTask{ @Override protected String doInBackground(String... arg) { return new Request(arg[0], arg[1], arg[2]).Content; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); WebTest.setText(s); } } }
Комментариев нет:
Отправить комментарий