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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris Harte2015 Top Expert (Most Article Points)Commented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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 Harte2015 Top Expert (Most Article Points)Commented:
Not finding a file is usually a permissions problem. Check your url and the permissions of the access to the server.
0
Chris Harte2015 Top Expert (Most Article Points)Commented:
No further input from the OP
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.