HttpURLConnection发送+而不是空格

时间:2015-09-02 10:22:22

标签: java http

我想将http post请求发送到某个服务器,参数包含空格以及一些特殊字符。以下是我的代码:

public static String HttpPost(String[] paramName, String[] paramVal)
{
    try{
    String parameters = null;
    if ((paramName != null ) && (paramVal != null))
    {
        parameters = paramName[0] +"="+ paramVal[0];
        for (int i = 1; i < paramName.length; i++) 
        {
            parameters+= "&";
            parameters += URLEncoder.encode(paramName[i], "US-ASCII") + "=" + URLEncoder.encode(paramVal[i], "utf-8");
        }
    }
    //parameters = URLEncoder.encode(parameters, "utf-8");
    byte[] postData = parameters.getBytes(StandardCharsets.US_ASCII);
    int postDataLength = postData.length;
    FolderManager fm = new FolderManager();
    String urlStr = FolderManager.ApplicationUnderTestUrl();
    URL url = new URL( urlStr );
    HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
    conn.setDoOutput( true );
    conn.setInstanceFollowRedirects( false );
    conn.setRequestMethod( "POST" );

    //con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
    conn.setRequestProperty("Accept", "application/x-www-form-urlencoded; charset=US-ASCII");
    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded; charset=US-ASCII"); 
    conn.setRequestProperty( "charset", "US-ASCII");
    conn.setRequestProperty("Accept-Encoding", "identity");
    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    conn.setUseCaches( false );
    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {

       wr.write( postData );
       //System.out.print(postData);
    }
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        System.out.println(line);
        return line;
    }

    reader.close(); 
    return line;
    }catch(Exception e)
    {
        return e.getMessage();
    }
} 

以上代码会发送特殊字符,但会发送&#39; +&#39;符号里面有空间的符号。我该如何避免这种情况?

1 个答案:

答案 0 :(得分:-1)

我得到了它的工作。这有助于:

from collections import Counter

def maximum_number(lst):
    return Counter(lst).most_common(1)[0][1]

希望它也能以某种方式帮助你。