java - 发送带有 URL 中的查询字符串的 HTTP Post

标签 java android http-post

我对使用查询字符串发送 HTTP Post 存在疑问。

我有下面的代码,但该代码不起作用。我尝试通过 Web 服务发送嵌入在 URL 中的用户和密码,但它不起作用。此代码无法连接到网络服务。

@Override
        protected String doInBackground(String... params) {

            String result = "";

            try {
                    URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user="+user+"&senha="+password);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");               


                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = bufferedReader.readLine()) != null) {
                        response.append(inputLine);
                    }

                    result = response.toString();
                    bufferedReader.close();
                } catch (Exception e) {
                    Log.d("InputStream", e.getMessage());
                    }

            return result;
        }

最佳答案

我认为你的意思是 GET 请求而不是 POST, 并且您应该对查询参数中的变量进行编码,在您的情况下为“用户”和“密码”。

URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user=" + URLEncoder.encode(user, "UTF-8")+"&senha="+ URLEncoder.encode(password, "UTF-8"));

关于java - 发送带有 URL 中的查询字符串的 HTTP Post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028636/

相关文章:

node.js - 将 request.post 的内容类型 header 设置为 json

引用 vararg (String[]...) 时,Javadoc @link 不起作用

android - 如何在线性布局中获取textview的位置(Y坐标)

java Lucene最佳匹配不是精确匹配

java - 无法下载aapt2-windows.jar(com.android.tools.build :aapt2:3.4.2-5326820): No cached version available for offline mode

android - 自定义警报对话框中的共享首选项

http-post - 如何使用身份验证 POST 到 ESP8266 上的 RESTful API?

http - 使用 LotusScript 发送 HTTP Post 请求

java - 为什么/何时添加 inputMismatchException?

java - Mac OS X 上的 JRE lib/security 目录在哪里?