最近项目中加了一个上传需求 用了几个框架发现跟后台总是不搭接 于是乎 还是用 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) { }
}
以上只是我个人用到的 具体里边的一些参数设置 用到时候 在去查看就好