向网站发送POST请求并收到结果

时间:2017-05-18 15:39:22

标签: android post request

我需要发送HTTP post请求并接收输出,但是当我运行应用程序时,应用程序崩溃了。

以下是我使用的代码。

public String getRequest(String url){         StringBuilder responseOutput = new StringBuilder();

try {
        URL uri = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)uri.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
        connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
        connection.setDoOutput(true);

        DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
        dStream.flush();
        dStream.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line = "";

        while((line = br.readLine()) != null ) {
            responseOutput.append(line);
        }
        br.close();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return responseOutput.toString();
}

这是崩溃日志。

05-18 16:34:50.915 18272-18272/com.prisonvoicemail.appupdater E/AndroidRuntime: 
FATAL EXCEPTION: main

  Process: com.prisonvoicemail.appupdater, PID: 18272

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.prisonvoicemail.appupdater/com.prisonvoicemail.appupdater.MainActivity}: android.os.NetworkOnMainThreadException

  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)

  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)

  at android.app.ActivityThread.-wrap11(ActivityThread.java)

  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)

  at android.os.Handler.dispatchMessage(Handler.java:102)

  at android.os.Looper.loop(Looper.java:148)

  at android.app.ActivityThread.main(ActivityThread.java:5443)

  at java.lang.reflect.Method.invoke(Native Method)

  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

    Caused by: android.os.NetworkOnMainThreadException

  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1287)

  at java.net.InetAddress.lookupHostByName(InetAddress.java:431)

  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)

  at java.net.InetAddress.getAllByName(InetAddress.java:215)

  at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)

  at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)

  at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)

  at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)

  at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)

  at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)

  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)

  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)

  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)

  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)

  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)

  at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)

  at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)

  at com.prisonvoicemail.appupdater.HTTPRequest.getRequest(HTTPRequest.java:72)

  at com.prisonvoicemail.appupdater.MainActivity.onCreate(MainActivity.java:79)

  at android.app.Activity.performCreate(Activity.java:6259)

  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)

  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)

  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 

  at android.app.ActivityThread.-wrap11(ActivityThread.java) 

  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 

  at android.os.Handler.dispatchMessage(Handler.java:102) 

  at android.os.Looper.loop(Looper.java:148) 

  at android.app.ActivityThread.main(ActivityThread.java:5443) 

  at java.lang.reflect.Method.invoke(Native Method) 

  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

2 个答案:

答案 0 :(得分:0)

Android dons不允许在主线程(控制ui)上进行网络调用以保持其自由,你需要做一些简单的多线程,你可以看看Asynctask进行该操作,或者使用外部图书馆,如Retrofit,Volley,Loopj等...

您可以从Asynctask开始第一课:

http://developer.android.com/reference/android/os/AsyncTask.html

将调用代码放在doinbackground(另一个线程而不是主线程)中,在获得结果并完成doinbackground之后,您将获得OnPost方法(在主线程上,您可以进行ui更改)这里)

希望它有所帮助。

答案 1 :(得分:0)

您有 NetworkOnMainThreadException ,这是因为您从应用程序主线程调用此方法。

您不应该在主线程中执行任何网络操作(阻塞操作),这将阻碍您的应用程序直到操作完成。此外,将函数调用包装在AsyncTask中,然后调用AsyncTask.execute(),这将解决您的问题。 e.g

AsyncTask task = new AsyncTask() {
    @Override
    protected Object doInBackground(Object[] params) {
        //do your stuff here
        return null;
    }
};
task.execute();

希望有所帮助。干杯:)