通过 HttpURLConnection 发送 post 数据崩溃并且无法正常工作

sending post data by HttpURLConnection crashes and don't work right

我想向服务器发送一些 json 数据。

我使用了 HttpURLConnection,但我的代码在以下行崩溃:

PrintWriter out = new PrintWriter(urlConnection.getOutputStream());

我想知道我的post数据到底有没有发送出去。

public void send(){
            String json ="some string";
            HttpURLConnection urlConnection = null;
            try {
                String postdata = "locs=" + URLEncoder.encode(json,"UTF-8");
                URL url = new URL("http://destination/");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setFixedLengthStreamingMode(postdata.getBytes().length);
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                urlConnection.setConnectTimeout(15000);

                PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
                out.print(postdata);
                out.close();

                String response= "";
                Scanner inStream = new Scanner(urlConnection.getInputStream());
                while(inStream.hasNextLine()){
                    response+=(inStream.nextLine());
                }
                Log.d("states",response);

            } catch (Exception e) {
                Log.d("states", e.getLocalizedMessage());
            }

    }

日志:

03-23 06:01:45.226: D/states(19731): CONNECTIVITY_CHANGE
03-23 06:01:45.226: D/states(19731): connected to internet
03-23 06:01:45.226: D/xxdalvikvm(19731): XX::Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy; was loaded
03-23 06:01:45.256: D/xxdalvikvm(19731): XX::Lcom/example/vatanatomy/loctype; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpHandler; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpURLConnectionImpl; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/RawHeaders; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/RawHeaders; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpEngine; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Ljava/net/CacheResponse; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpEngine; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Ljava/net/ResponseCache; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/RequestHeaders; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HeaderParser$CacheControlHandler; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/RequestHeaders; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Ljava/net/CookieHandler; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Ljava/net/ResponseSource; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpConnection; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpConnectionPool; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Llibcore/net/http/HttpConnection$Address; was loaded
03-23 06:01:45.276: D/xxdalvikvm(19731): XX::Landroid/os/NetworkOnMainThreadException; was loaded
03-23 06:01:45.306: D/xxdalvikvm(19731): XX::Ljava/lang/reflect/InvocationTargetException; was loaded
03-23 06:01:45.306: D/AndroidRuntime(19731): Shutting down VM
03-23 06:01:45.306: W/dalvikvm(19731): threadid=1: thread exiting with uncaught exception (group=0x40fd02a0)
03-23 06:01:45.306: D/xxdalvikvm(19731): XX::Ljava/net/UnknownHostException; was loaded
03-23 06:01:45.316: E/AndroidRuntime(19731): FATAL EXCEPTION: main
03-23 06:01:45.316: E/AndroidRuntime(19731): java.lang.RuntimeException: Unable to start receiver com.example.vatanatomy.StartMyServiceAtBootReceiver: java.lang.NullPointerException: println needs a message
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2287)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.app.ActivityThread.access00(ActivityThread.java:140)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.os.Looper.loop(Looper.java:137)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.app.ActivityThread.main(ActivityThread.java:4921)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at java.lang.reflect.Method.invokeNative(Native Method)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at java.lang.reflect.Method.invoke(Method.java:511)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at dalvik.system.NativeStart.main(Native Method)
03-23 06:01:45.316: E/AndroidRuntime(19731): Caused by: java.lang.NullPointerException: println needs a message
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.util.Log.println_native(Native Method)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.util.Log.d(Log.java:155)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at com.example.vatanatomy.senddata.send(senddata.java:92)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at com.example.vatanatomy.StartMyServiceAtBootReceiver.onReceive(StartMyServiceAtBootReceiver.java:22)
03-23 06:01:45.316: E/AndroidRuntime(19731):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
03-23 06:01:45.316: E/AndroidRuntime(19731):    ... 10 more
03-23 06:01:56.396: I/Process(19731): Sending signal. PID: 19731 SIG: 9

编辑: 我将代码更改为以下。但在第二个日志应用程序将再次崩溃之前:(

public void send(){
            String json = "some string";
Log.d("states", "1");
                AsyncHttpClient client = new AsyncHttpClient();
Log.d("states", "2");
            RequestParams params = new RequestParams();
            params.put("locs", json);

            client.post("http://domain.com/", params, new AsyncHttpResponseHandler() {
                 @Override
                 public void onStart() {
                     Log.d("states", "AsyncHttpClient start");
                 }

                 @Override
                 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                     Log.d("states", "AsyncHttpClient onSuccess "+statusCode);
                 }

                 @Override
                 public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
                 {
                     Log.d("states", "AsyncHttpClient onFailure "+statusCode);
                 }

                 @Override
                 public void onRetry(int retryNo) {
                     Log.d("states", "AsyncHttpClient onRetry "+retryNo);
                 }

                 @Override
                 public void onProgress(int bytesWritten, int totalSize) {
                     Log.d("states", "AsyncHttpClient onProgress "+totalSize);
                 }

                 @Override
                 public void onFinish() {
                     Log.d("states", "AsyncHttpClient onFinish ");
                 }

            });


    }

日志:

03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/LocationDetector; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/db/db; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/db/MySQLiteHelper; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteDatabaseConfiguration; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnectionPool; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnection$OperationLog; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnection$Operation; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnection$PreparedStatementCache; was loaded
03-23 13:28:05.708: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnection$PreparedStatement; was loaded
03-23 13:28:05.718: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteStatementInfo; was loaded
03-23 13:28:05.718: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteSession; was loaded
03-23 13:28:05.718: D/xxdalvikvm(4073): XX::Landroid/database/sqlite/SQLiteConnectionPool$AcquiredConnectionStatus; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/Criteria; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/Criteria; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/ILocationListener; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/ILocationListener$Stub; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/LocationManager$ListenerTransport; was loaded
03-23 13:28:05.728: D/xxdalvikvm(4073): XX::Landroid/location/LocationManager$ListenerTransport; was loaded
03-23 13:28:08.801: D/xxdalvikvm(4073): XX::Landroid/sec/clipboard/ClipboardExManager; was loaded
03-23 13:28:08.811: D/xxdalvikvm(4073): XX::Landroid/sec/clipboard/IClipboardService; was loaded
03-23 13:28:08.811: D/xxdalvikvm(4073): XX::Landroid/sec/clipboard/IClipboardService$Stub; was loaded
03-23 13:28:08.811: D/xxdalvikvm(4073): XX::Landroid/sec/clipboard/IClipboardService$Stub$Proxy; was loaded
03-23 13:28:09.472: W/egl_server(4073): Allocating storage 1x1 surface type 0x1
03-23 13:28:09.512: D/xxdalvikvm(4073): XX::Landroid/view/HardwareRenderer$Gl20Renderer; was loaded
03-23 13:28:24.436: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/StartMyServiceAtBootReceiver; was loaded
03-23 13:28:24.436: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/senddata; was loaded
03-23 13:28:24.436: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/devices/Devices; was loaded
03-23 13:28:24.436: E/dalvikvm(4073): Could not find class 'com.loopj.android.http.AsyncHttpClient', referenced from method com.example.vatanatomy.senddata.send
03-23 13:28:24.436: W/dalvikvm(4073): VFY: unable to resolve new-instance 890 (Lcom/loopj/android/http/AsyncHttpClient;) in Lcom/example/vatanatomy/senddata;
03-23 13:28:24.436: D/dalvikvm(4073): VFY: replacing opcode 0x22 at 0x0087
03-23 13:28:24.436: D/xxdalvikvm(4073): XX::Lcom/example/vatanatomy/loctype; was loaded
03-23 13:28:24.436: D/dalvikvm(4073): DexOpt: unable to opt direct call 0x1814 at 0x89 in Lcom/example/vatanatomy/senddata;.send
03-23 13:28:24.436: D/dalvikvm(4073): DexOpt: unable to opt direct call 0x1817 at 0x95 in Lcom/example/vatanatomy/senddata;.send
03-23 13:28:24.436: W/dalvikvm(4073): Unable to resolve superclass of Lcom/example/vatanatomy/senddata; (891)
03-23 13:28:24.436: W/dalvikvm(4073): Link of class 'Lcom/example/vatanatomy/senddata;' failed
03-23 13:28:24.436: D/dalvikvm(4073): DexOpt: unable to opt direct call 0x180a at 0xa1 in Lcom/example/vatanatomy/senddata;.send
03-23 13:28:24.446: D/states(4073): CONNECTIVITY_CHANGE
03-23 13:28:24.446: D/states(4073): connected to internet
03-23 13:28:24.446: D/xxdalvikvm(4073): XX::Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy; was loaded
03-23 13:28:24.496: D/dalvikvm(4073): GC_CONCURRENT freed 75K, 7% free 9760K/10439K, paused 31ms+2ms, total 47ms
03-23 13:28:24.496: D/dalvikvm(4073): WAIT_FOR_CONCURRENT_GC blocked 16ms
03-23 13:28:24.526: D/dalvikvm(4073): GC_CONCURRENT freed 75K, 7% free 10206K/10887K, paused 2ms+3ms, total 20ms
03-23 13:28:24.526: D/dalvikvm(4073): WAIT_FOR_CONCURRENT_GC blocked 15ms
03-23 13:28:24.556: D/states(4073): 1
03-23 13:28:24.556: D/xxdalvikvm(4073): XX::Ljava/lang/reflect/InvocationTargetException; was loaded
03-23 13:28:24.556: D/AndroidRuntime(4073): Shutting down VM
03-23 13:28:24.556: W/dalvikvm(4073): threadid=1: thread exiting with uncaught exception (group=0x40fd02a0)
03-23 13:28:24.556: D/xxdalvikvm(4073): XX::Ljava/net/UnknownHostException; was loaded
03-23 13:28:24.566: E/AndroidRuntime(4073): FATAL EXCEPTION: main
03-23 13:28:24.566: E/AndroidRuntime(4073): java.lang.NoClassDefFoundError: com.loopj.android.http.AsyncHttpClient
03-23 13:28:24.566: E/AndroidRuntime(4073):     at com.example.vatanatomy.senddata.send(senddata.java:103)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at com.example.vatanatomy.StartMyServiceAtBootReceiver.onReceive(StartMyServiceAtBootReceiver.java:22)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.app.ActivityThread.access00(ActivityThread.java:140)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.os.Looper.loop(Looper.java:137)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at android.app.ActivityThread.main(ActivityThread.java:4921)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at java.lang.reflect.Method.invokeNative(Native Method)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at java.lang.reflect.Method.invoke(Method.java:511)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
03-23 13:28:24.566: E/AndroidRuntime(4073):     at dalvik.system.NativeStart.main(Native Method)

您确定目的地 link 是真的吗?为什么不使用像 Volley or Loopj's Async HttpClient

这样的库

Loopj 的异步 HttpClient 示例:

String url = "http://www.example.com"
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");

client.post(url, params, new AsyncHttpResponseHandler() {
 @Override
 public void onStart() {
     // Initiated the request
 }

 @Override
 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
     // Successfully got a response
 }

 @Override
 public void onFailure(int statusCode, Header[] headers, byte[]     
 responseBody, Throwable
 error)
 {
     // Response failed :(
 }

 @Override
 public void onRetry(int retryNo) {
     // Request was retried
 }

 @Override
 public void onProgress(int bytesWritten, int totalSize) {
     // Progress notification
 }

 @Override
 public void onFinish() {
     // Completed the request (either success or failure)
 });