Post http and get returned/echoed data in Android studio

My code doesn't seem to send the post/get on my android app. I don't get anything from both ends which one is my server and also on my phone there is no respond sent but the studio just disconect from my phone its says application has terminated but my application is running but its sort of freeze. Here is my code.

try {
            final TextView outputView = (TextView) findViewById(R.id.tvresult);
            URL url = new URL("http://www.myurlhere/myfile.php");

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

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

             //Map<String, List<String>> headerFields = connection.getHeaderFields();
             //List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);



            String urlParameters = "user=Admin&code=123";

            //connection.connect();

            DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
            dStream.writeBytes(urlParameters);
            dStream.flush();

            //dStream.close();

            int responseCode = connection.getResponseCode();
            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
            output.append(System.getProperty("line.separator") + "Response Code "+ responseCode);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            while((line = br.readLine()) !=null){
                responseOutput.append(line);
            }
            br.close();

            //output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

            MainActivity.tvresult.setText(responseOutput.toString());

            //if(cookiesHeader != null) {
                //for (String cookie : cookiesHeader) {
                 //   msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
               // }
           // }
            //conn.addHeader("Cookie", "__test=d185379fafb00707c79e750ec3a26207; expires=Thursday, December 31, 2037, 3:55:55 PM; path=/");
           // if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
             //   connection.setRequestProperty("Cookie",
             //           TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));

            //}
dStream.close();
           //outputView.setText(output);

           /// URL url = new URL("http:/myurl/myfile.php?");
           /// JSONObject postDataParams = new JSONObject();
           /// postDataParams.put("name", "just");
           /// Log.e("params", postDataParams.toString());

           /// HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //conn.setRequestMethod("POST");

           /// Map<String, List<String>> headerFields = conn.getHeaderFields();
           /// List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

           /// if(cookiesHeader != null) {
             ///   for (String cookie : cookiesHeader) {
             ///       msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
             ///   }
           /// }
            //conn.addHeader("Cookie", "__test=xxxxxxxxx; expires=Thursday, December 31, 2037, 3:55:55 PM; path=/");
           /// if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            ///    conn.setRequestProperty("Cookie",
            ///            TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));
           /// }
           /// conn.setReadTimeout(15000 /* milliseconds */);
           /// conn.setConnectTimeout(15000 /* milliseconds */);
           /// conn.setDoOutput(true);
            //conn.setDoInput(true);
           /// OutputStream os = conn.getOutputStream();
           /// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
           /// writer.write(getPostDataString(postDataParams));

           /// writer.flush();
           /// writer.close();
           /// os.close();

           /// int responseCode=conn.getResponseCode();
            ///if(responseCode == HttpURLConnection.HTTP_OK){
               /// BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
               /// StringBuffer sb = new StringBuffer("");
               /// String line = "";
                ///while ((line = in.readLine()) != null){
                ///    sb.append(line);
               ///     break;
               /// }
               /// in.close();
                //return sb.toString();"Message Sent."
               /// MainActivity.tvresult.setText(sb.toString());
            ///}else{
                //return new String("false : " +responseCode);
                ///MainActivity.tvresult.setText("Nor HTTP_OK");
                //MainActivity.tvresult.append(,responseCode);
            ///}
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        //}catch (JSONException e){
           // e.printStackTrace();
        } catch (NetworkOnMainThreadException e){
            //MainActivity.tvresult.setText(e);
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

Open in new window

LVL 2
Mlungisi NdlelaFounder of MCSIDevelopers also a software developerAsked:
Who is Participating?
 
Chris HarteConnect With a Mentor ThaumaturgeCommented:
I cannot see anything obvious with the code BUT connections to the internet should be inside an AsyncTask. The responseOutput should be returned from the doInBackground() method which will then be automatically picked up by the onPostExecute() method.

https://developer.android.com/training/basics/network-ops/connecting.html
0
 
Mlungisi NdlelaFounder of MCSIDevelopers also a software developerAuthor Commented:
Hi. Thanks. Well I'm new to Android but I have seen some posts which shows this with AsyncTask but the reason why I put my connection code the way I put it is that I try to send the scanned data to the server just when the scan is done. Now I didn't know how to create asyncTask class that can take argument which will beparameter that will hold my scanned data.

Thank you.
0
 
Mlungisi NdlelaFounder of MCSIDevelopers also a software developerAuthor Commented:
Ow and currently I keep getting an error that a file can't be found I've changed hosts but still its says file not found. Any known reason for this because the file is there on my servers but with Android App its keep showing error of file not found.
0
 
Chris HarteThaumaturgeCommented:
Not finding a file is usually a permissions problem. Check your url and the permissions of the access to the server.
0
 
Chris HarteThaumaturgeCommented:
No further input from the OP
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.