Android - HttpURLConnection POST参数不起作用

时间:2015-11-18 09:18:09

标签: android web-services android-networking androidhttpclient

我正在使用HttpURLConnection与我的一个Android App,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;

}

2 个答案:

答案 0 :(得分:1)

使用以下代码更改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

答案 1 :(得分:0)

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

port:80