5

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.

5
  • if you want to maintain minSdk version , maybe it's not problem to use deprecated methods. Commented Mar 31, 2015 at 18:15
  • Well I only need to target Android 4.1+ at the moment, if there is a one solution that fits all, and does not use deprecated stuff, that is what I would like to do. Also, I am OCD, I don't like lines going thru my code telling me things are deprecated.. Commented Mar 31, 2015 at 18:17
  • You can use annotations like @SuppressLint or ` @TargetApi(22)` to use newer library, and use @suppresswarnings to clear that warnints. I think that would't be bad decision. Commented Mar 31, 2015 at 18:25
  • I know, I know, I don't like those either. :D Usually something is deprecated for a reason, so I would like to update when possible. And in this case, Google recommended this change like 3 years ago. Commented Mar 31, 2015 at 18:26
  • 1
    I also hate the tricking with code like this, but sometimes it's inevitable. Hope you find your answer, good luck! Commented Mar 31, 2015 at 18:29

1 Answer 1

7

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.