Android - HttpURLConnection POST 参数不起作用

Android - HttpURLConnection POST parameters not working

我在我的一个 android 应用程序中使用 HttpURLConnection 与 Web 服务通信,GET 方法和参数已正确提交,但是当我尝试 POST 请求 POST 参数时没有在请求中提交。我附上了使用的方法,请指导我哪里出错了。

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String request_url, int method,
                              Map<String,String> params) {
    InputStream inputStream = null;

    HttpURLConnection urlConnection = null;

    Integer result = 0;
    try {
        URL url = new URL(request_url);
        urlConnection = (HttpURLConnection) url.openConnection();
        //urlConnection.setRequestProperty("Content-Type", "application/xml");
        //urlConnection.setRequestProperty("Accept", "application/xml");
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        if (method == GET) {
            urlConnection.setRequestMethod("GET");
        } else if(method == POST) {
            urlConnection.setRequestMethod("POST");
            String urlParameters = null;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if(urlParameters != null)
                {
                    urlParameters += "&";
                }
                urlParameters +=entry.getKey() +"="+ URLEncoder.encode(entry.getValue(), "UTF-8");
            }
            Log.d(TAG, "urlParameters: "+urlParameters);
            //Send request
            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(urlParameters);
            writer.flush ();
            writer.close ();
        }
        int statusCode = urlConnection.getResponseCode();
        if (statusCode == HttpsURLConnection.HTTP_OK) {

            inputStream = new BufferedInputStream(urlConnection.getInputStream());

            response = convertInputStreamToString(inputStream);


            result = 1; // Successful

        } else {
            result = 0; //"Failed to fetch data!";
        }

    } catch (Exception e) {
        Log.d(TAG, ""+e.getLocalizedMessage());
        e.printStackTrace();
    }
    Log.d(TAG, ""+response);
    return response;

}

尝试关闭您的 OutputStream 并在完成编写器后调用 httpURLConnection.connect():

...
writer.flush();
writer.close();
os.close();
urlConnection.connect();
...

使用以下代码更改您的 urlParameters 形成逻辑:

StringBuilder result = new StringBuilder();
try {
    for (Map.Entry<String, String> param : params.entrySet()){
        if (result.toString().length() !=0) {
            result.append("&");
        }
        result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
     }
} catch (UnsupportedEncodingException e) {
     e.printStackTrace();
}

在你的代码中

 urlParameters = null;
 urlParameters +=entry.getKey() +"="+ URLEncoder.encode(entry.getValue(), "UTF-8");

将在 urlParameters 的开头添加 null 字符串。建议在循环中使用 StringBuilder 代替 String concatenation