Passing Parameters with HttpURLConnection

前端 未结 1 421
生来不讨喜
生来不讨喜 2021-01-19 00:21

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

Using openConnection() seems pretty straight f

相关标签:
1条回答
  • 2021-01-19 01:12

    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();
    
    0 讨论(0)
提交回复
热议问题