关于 HttpURLConnection POST请求 上传 以及中文乱码问题
来源:互联网 发布:k歌达人 网络异常 编辑:程序博客网 时间:2024/06/05 13:17
最近项目中加了一个上传需求 用了几个框架发现跟后台总是不搭接 于是乎 还是用 HttpURLConnection 但是也碰到了许多坑
框架用多了 忘记了首先需要开启一个子线程 new Thread();\
以下为集中POST请求方式
POST 表单请求
- public String posts(String url, < Map String >, String form) {
HttpURLConnection conn = null;
PrintWriter pw = null;
BufferedReader rd = null;
StringBuilder out = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = null;
String response = null;
for (String key : form.keySet()) {
if (out.length() != 0) {
out.append(“&”);
}
out.append(key).append(“=”).append(form.get(key));
}
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(“POST”);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
conn.setRequestProperty(“Content-Type”,
“application/x-www-form-urlencoded”);
conn.connect();
pw = new PrintWriter(conn.getOutputStream());
pw.print(out.toString());
pw.flush();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”));
while ((line = rd.readLine()) != null) {
sb.append(line);
}
response = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pw != null) {
pw.close();
}
if (rd != null) {
rd.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
POST JSON请求
//post字符串请求 没用到
public String post(String url, String rawBody) {
HttpURLConnection conn = null;
PrintWriter pw = null;
BufferedReader rd = null;
StringBuilder sb = new StringBuilder();
String line = null;
String response = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(“POST”);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setRequestProperty(“Content-Type”,
“application/x-www-form-urlencoded”);
conn.setUseCaches(false);
conn.connect();
pw = new PrintWriter(conn.getOutputStream());
pw.print(rawBody);
pw.flush();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”));
while ((line = rd.readLine()) != null) {
sb.append(line);
}
response = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pw != null) {
pw.close();
}
if (rd != null) {
rd.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
上传文件private void upLoadByCommonPost(String path) {
String end = "\r\n";String twoHyphens = "--";String boundary = "******";try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = null; httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K // 允许输入输出流 httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); // 使用POST方法 httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream( httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"multipartFile\"; filename=\"" + path.substring(path.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(path); byte[] buffer = new byte[8192]; // 8k int count = 0; // 读取文件 while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String result = br.readLine(); Log.i("--superme:ok>>", result); dos.close(); is.close();} catch (Exception e) { e.printStackTrace(); Log.i("--superme:no>>", e.getMessage());}
}
上边的这种有时候可能出现乱码 那么 还有下边
private void upLoadFilePost(String path) {
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求HttpPost post = new HttpPost(uploadUrl);//创建 HTTP POST 请求MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式builder.addBinaryBody("multipartFile", new File(path));StringBody stringBody = new StringBody("中文乱码", contentType);builder.addPart("test", stringBody);HttpEntity entity = builder.build();// 生成 HTTP POST 实体post.setEntity(entity);//设置请求参数HttpResponse response = null;// 发起请求 并返回请求的响应try { response = client.execute(post);} catch (IOException e) { e.printStackTrace();}if (response.getStatusLine().getStatusCode() == 200) {}
}
以上只是我个人用到的 具体里边的一些参数设置 用到时候 在去查看就好
- 关于 HttpURLConnection POST请求 上传 以及中文乱码问题
- HttpUrlConnection post方法传递中文乱码问题
- 关于Get,Post请求中文乱码问题有效解决方法
- Java的HttpURLConnection通过POST请求中文乱码
- get/post请求:中文乱码问题
- get/post请求中文乱码问题
- post与get请求中文乱码问题
- SpringMVC-Post/Get请求中文乱码问题
- SpringMvc发送post请求中文乱码问题
- get,post请求中文乱码问题
- Java HttpURLConnection模拟请求Rest接口解决中文乱码问题
- Java采用HttpURLConnection请求调用服务时中文乱码问题
- HttpURLConnection以及GBK转UTF-8中文部分乱码问题
- Spring学习笔记(三十五):关于httpClient的post请求,到后台中文乱码的问题
- 利用HttpURLConnection发送post请求上传文件
- 使用HttpUrlConnection进行post请求上传文件
- 利用HttpURLConnection发送post请求上传文件
- 利用HttpURLConnection发送post请求上传文件
- iOS Bundle的简单使用
- mysql-5.7.11-winx64.zip 安装配置
- Python 生成随机数
- Discuz!后台程序目录/source/admincp/下目录及文件功能详解
- 不要用for in语句对数组进行遍历
- 关于 HttpURLConnection POST请求 上传 以及中文乱码问题
- 1001. A+B Format (20)
- 解决Qt Designer.exe启动后,界面不显示的问题
- TCP的连接和断开详解
- JavaScript从作用域到闭包
- 特殊字符html,css转义大全
- 过拟合、正则
- Sigmoid 函数和 Tanh 函数的区别
- Halcon学习(二) Halcon基本操作:批量读入本地文件夹内的图片