0

I try to connect to my API , and post some JSON dat to DB , I follow this one but some how ,

Connection.connect();  //get Respone Message : Null

the connection get Null , but I use postman test this API , it work , respone 200 OK , I use debug mode and it JSON is in it , URL is right , please help

UPDATE : I find out this but if I add Strick mode , it will show tons of error , so I'm trying to set Click in DoinBackGround , but not sure I can use click in background or not

Update : this work , have to set below setcontentview , but data did not sent to database , keep trying...

Debug mode : it stop at int HttpResult = Connection.getResponseCode(); than jump to catch (IOException e) { keep trying...

code

    public void onClick(View v) {
            HttpURLConnection Connection = null;
            try {
                StringBuilder sb = new StringBuilder();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("artist", artist.getText().toString());
                jsonObject.put("weeksAtOne", week.getText().toString());
                jsonObject.put("decade", year.getText().toString());
                jsonObject.put("song", song.getText().toString());
                String http = "http://36.224.137.68:3000/songs";

                URL url = new URL(http);
                Connection = (HttpURLConnection) url.openConnection();
                Connection.setDoOutput(true);
                Connection.setRequestMethod("POST");
                Connection.setUseCaches(false);
                Connection.setConnectTimeout(10000);
                Connection.setReadTimeout(10000);
                Connection.setRequestProperty("Content-Type", "application/json");
                Connection.connect();  //null here
                OutputStreamWriter out = new OutputStreamWriter(Connection.getOutputStream());
                out.write(jsonObject.toString());
                out.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
                out.flush();
                out.close();
                int HttpResult = Connection.getResponseCode();
                if (HttpResult == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            Connection.getInputStream(), "utf-8"));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();

                    System.out.println("" + sb.toString());

                } else {
                    System.out.println(Connection.getResponseMessage());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }finally{
                if(Connection!=null)
                    Connection.disconnect();
            }

debug mode message

 this = {UploadJSON$1@18566} 
 v = {Button@18568} "android.widget.Button{3094c1bd VFED..C. ...P....      272,364-448,460 #7f0d00f2 app:id/btUpload}"
 Connection = {HttpURLConnectionImpl@18571}  "com.android.okhttp.internal.http.HttpURLConnectionImpl:http://36.224.137.68:300 0/songs"
 sb = {StringBuilder@18572} ""
 jsonObject = {JSONObject@18573} "  {"artist":"Yyyyyyy","weeksAtOne":"Ttttt","decade":"Hhhhh","song":"Ooooo"}"
 http = {String@18574} "http://36.224.137.68:3000/songs"
 url = {URL@18575} "http://36.224.137.68:3000/songs"
 authority = {String@18585} "36.224.137.68:3000"
 file = {String@18586} "/songs"
 hashCode = 0
 host = {String@18587} "36.224.137.68"
 path = {String@18586} "/songs"
 port = 3000
 protocol = {String@18588} "http"
 query = null
 ref = null
 streamHandler = {HttpHandler@18589} 
 userInfo = null
 shadow$_klass_ = {Class@1635} "class java.net.URL"
 shadow$_monitor_ = -1215925588

error

com.addtw.aweino1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.addtw.aweino1, PID: 4890
                                                             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:154)
                                                                 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:1185)
                                                                 at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:395)
                                                                 at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
                                                                 at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
                                                                 at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
                                                                 at com.addtw.aweino1.UploadJSON$1.onClick(UploadJSON.java:74)
                                                                 at android.view.View.performClick(View.java:5076)
                                                                 at android.view.View$PerformClick.run(View.java:20279)
                                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                 at android.os.Looper.loop(Looper.java:135)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                 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:1405)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Community
  • 1
  • 1
Awei Hsue
  • 257
  • 5
  • 19
  • `the connection get Null` what do you mean? – njzk2 Feb 20 '16 at 01:06
  • Sorry for this, it mean, connection.connect() respone a null, so cannot connect – Awei Hsue Feb 20 '16 at 01:08
  • that does not make sense. `connect()` is a void, so it does not return anything, null or otherwise. And if `Connection` was null, a/ it would crash before that b/ it would appear as null in your debugger, which obviously it does not. Do you have an actual exception happening? – njzk2 Feb 20 '16 at 03:28

1 Answers1

0

Can you trying adding Host property as below before connection.connect(); urlConnection.setRequestProperty("Host", "36.224.137.68");

Nitin Prabhu
  • 624
  • 6
  • 10