用java写了一个Http client,但向服务器post的时候传中文参数老是乱码,请大侠明示一下

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用java写了一个Http client,但向服务器post的时候传中文参数老是乱码,请大侠明示一下相关的知识,希望对你有一定的参考价值。

...
con.setRequestProperty( "Content-Type","application/x-www-form-urlencoded" );
//这样加属性也是不行
...
String para = "Title=中国"+"&Data=人民";
//URLEncoder.encode(para)也不行
...
con.setDoOutput( true );
OutputStreamWriter out = new OutputStreamWriter( con.getOutputStream() );
out.write( para );
out.flush();

请大侠指点一下!
谢谢!
补充一下啊 ,服务器端我没法改的,只能在客户端想办法!!!!!!!!!

以上的2个方法最好都要用上 过滤器只能解决POST请求 ,要处理GET请求就要用
bytes = string.getBytes("iso-8859-1") 得到原始的字节串,再用 string = new String(bytes, "GB2312") 重新得到正确的字符串 。
这个方法,所以最好2个都要写,这样不管是POST还是GET请求就都能解决了。
参考技术A 写个过滤器就行了。将编码格式写在web.xml的配置文件里。
下面的这个过滤器是tomcat提供的。
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;

/**
* <p>Example filter that sets the character encoding to be used in parsing the
* incoming request, either unconditionally or only if the client did not
* specify a character encoding. Configuration of this filter is based on
* the following initialization parameters:</p>
* <ul>
* <li><strong>encoding</strong> - The character encoding to be configured
* for this request, either conditionally or unconditionally based on
* the <code>ignore</code> initialization parameter. This parameter
* is required, so there is no default.</li>
* <li><strong>ignore</strong> - If set to "true", any character encoding
* specified by the client is ignored, and the value returned by the
* <code>selectEncoding()</code> method is set. If set to "false,
* <code>selectEncoding()</code> is called <strong>only</strong> if the
* client has not already specified an encoding. By default, this
* parameter is set to "true".</li>
* </ul>
*
* <p>Although this filter can be used unchanged, it is also easy to
* subclass it and make the <code>selectEncoding()</code> method more
* intelligent about what encoding to choose, based on characteristics of
* the incoming request (such as the values of the <code>Accept-Language</code>
* and <code>User-Agent</code> headers, or a value stashed in the current
* user's session.</p>
*
* @author Craig McClanahan
* @version $Revision: 466607 $ $Date: 2006-10-21 17:09:50 -0600 (Sat, 21 Oct 2006) $
*/

public class SetCharacterEncodingFilter implements Filter

// ----------------------------------------------------- Instance Variables

/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;

/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;

/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;

// --------------------------------------------------------- Public Methods

/**
* Take this filter out of service.
*/
public void destroy()

this.encoding = null;
this.filterConfig = null;



/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException

// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null))
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);


// Pass control on to the next filter
chain.doFilter(request, response);



/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException

this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;



// ------------------------------------------------------ Protected Methods

/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request)

return (this.encoding);



参考技术B bytes = string.getBytes("iso-8859-1") 得到原始的字节串,再用 string = new String(bytes, "GB2312") 重新得到正确的字符串 。

java中常见http client配置代理

工作用一个http client 去调用第三方的接口看起来很简单,但往往由于公司的网络安全要求,没法直接访问,需要配置一个代理才能连接外网,本篇给出三种常用的http client配置代理案例,使用时直接套用即可。

HttpURLConnection

这种方法用于纯java SE,但现在基本不用了,当前都是建立在框架的基础之上,所以只需要了解即可。

//url为接口地址
URL realUrl = new URL(url);
//根据公司的安全规范,配置代理,其中port是对外开放的端口,ip是公司给定的
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip,port));
HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection(proxy);
===配置请求属性,请求方法等===
//建立连接			
conn.connect();

RestTemplate

随着响应式编程的走红,RestTemplate也正逐步退出历史舞台,但用的人还是很多,通常情况下都是通过注入bean的形式来定义RestTemplate

 @Bean
 public RestTemplate restTemplate()
    	//根据公司的安全规范,配置代理,其中port是对外开放的端口,ip是公司给定的
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
        //将代理配置到工厂中
        SimpleClientHttpRequestFactory clientFactory = new SimpleClientHttpRequestFactory();
        clientFactory.setProxy(proxy);
        clientFactory.setConnectTimeout(5000);
        return new RestTemplate(clientFactory);
     

WebClient

WebClient支持响应式编程,正在逐步走红,其代理的配置原理大同小异。

//这里需要注意一下这两个包,都是来自己reactor的,不要引错了。
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;

  @Bean
  public WebClient proxy()    
         HttpClient httpClient = HttpClient.create().proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP).host(ip).port(port));
        return  WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .build();
    

总结

内容很简单,希望本文能帮助大家,祝大家在IT之路上少走弯路,一路绿灯不堵车,测试一性通过,bug秒解!

以上是关于用java写了一个Http client,但向服务器post的时候传中文参数老是乱码,请大侠明示一下的主要内容,如果未能解决你的问题,请参考以下文章

如何强制 http.client 在 python 中发送分块编码的 HTTP 正文?

JAVA通过http访问其他服务端API。

SpringCloud负载均衡笔记

java中常见http client配置代理

java中常见http client配置代理

Apache 或其他一些 CLIENT JAVA 实现是不是支持 HTTP/2?