我在用HttpURLConection发送POST请求时,并未包含中文,但自己测试时收到的请求前面总是包含几个乱码,求高手解决!代码如下:
public class HttpUtil {
/**
* 发送http POST请求
* @param httpUrl 请求URL
* @param httpContext 请求报文主体内容
* @return
* @throws IOException
*/
public static String sendPost(String httpUrl,String httpContext) throws IOException{
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false;
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json; encoding=utf-8");
connection.setRequestProperty("Connection", "keep-alive");
OutputStream out = connection.getOutputStream();
// 现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(httpContext); // 向对象输出流写出数据,这些数据将存到内存缓冲区中
out.close();
objOut.close(); // 关闭对象输出流
InputStream in = connection.getInputStream();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inr);
StringBuffer result = new StringBuffer();
String temp;
while((temp = reader.readLine()) != null){
result.append(temp);
}
in.close();
return result.toString();
}
String path = "http://。。。";// 实验环境中使用pc的ip,不能用localhost或127.0.0.1
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestProperty("Accept-Charset", "GBK");
conn.setRequestProperty("contentType", "GBK");
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
// readLesoSysXML(inStream);
BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "GBK"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
String str = buffer.toString();
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。