Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters with HttpURLConnection

With the old Apache stuff deprecated in API 22, I am finally getting around to updating my network stuff.

Using openConnection() seems pretty straight forward. However, I have not seen any good example to send parameters with it.

How would I update this code?

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("user_id",String.valueOf(userId)));
        httpPost.setEntity(new UrlEncodedFormEntity(param));

Now that NameValuePair and BasicNameValuePair are also deprecated.

EDIT: My server side php code doesn't expect JSON parameters and I can't all of the sudden switch due to existing users -- so a non-JSON answer is recommended.

EDIT2: I just need to Target Android 4.1+ at the moment.

like image 653
TheLettuceMaster Avatar asked Mar 31 '15 17:03

TheLettuceMaster


People also ask

How do I pass a query parameter in HttpURLConnection?

Here is some code to add query parameters into an HTTP request using Java: URL url = new URL("https://api.github.com/users/google"); HttpURLConnection con = (HttpURLConnection) url. openConnection(); con. setRequestMethod("POST"); con.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.


1 Answers

I fixed it like this:

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

Here is parameter stuff:

        String charset = "UTF-8";
        String s = "unit_type=" + URLEncoder.encode(MainActivity.distance_units, charset);
        s += "&long=" + URLEncoder.encode(String.valueOf(MainActivity.mLongitude), charset);
        s += "&lat=" + URLEncoder.encode(String.valueOf(MainActivity.mLatitude), charset);
        s += "&user_id=" + URLEncoder.encode(String.valueOf(MyndQuest.userId), charset);

        conn.setFixedLengthStreamingMode(s.getBytes().length);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(s);
        out.close();
like image 60
TheLettuceMaster Avatar answered Oct 28 '22 06:10

TheLettuceMaster