1. 如果请求中只携带参数:
public String httpPost(String urlStr, String params) {
byte[] data = null;
try {
data = params.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
return null;
}
URL url = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
String response = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(METHOD_POST);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.connect();
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HTTP_OK) {
inputStream = connection.getInputStream();
response = getResponse(inputStream);
} else {
response = "返回码:" + responseCode;
}
Log.e(Constant.ErrorTag.register.toString(),"服务器返回字符串 "+response);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return response;
}
2. 参数中携带参数及文件:
String CRLF = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection con = null;
InputStream is = null;
DataOutputStream ds = null;
FileInputStream videoFis = null;
FileInputStream imageFis = null;
try {
String urlStr = Constant.baseURL;
urlStr += Constant.UPLOAD_ACTION_PATH;
URL url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
con.setChunkedStreamingMode(0);
/* 设置DataOutputStream */
ds = new DataOutputStream(con.getOutputStream());
<strong> // Send normal param.</strong>
ds.writeBytes(twoHyphens + boundary + CRLF);
ds.writeBytes("Content-Disposition: form-data; name=\"param\""+CRLF);
ds.writeBytes("Content-Type: text/plain; charset=" + "UTF-8"+CRLF);
<pre name="code" class="java"> ds.flush();
ds.writeBytes(twoHyphens + boundary + CRLF);
int index = uploadFile.lastIndexOf(".");
String newName = "";
String thumbnailName = "";
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
if (Constant.VIDEO.equals(type)) {
newName = userId + "-video." + uploadFile.substring(index+1,uploadFile.length());
thumbnailName = userId + "-thumbnail.jpg";//send video file
ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_VIDEO_FROM_CLIENT+"\";filename=\"" + newName + "\"" + CRLF);
ds.writeBytes(CRLF);
videoFis = new FileInputStream(uploadFile);
int length = -1;
while ((length = videoFis.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(CRLF);
ds.writeBytes(twoHyphens + boundary + CRLF); //send thumbnail
ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_IMAGE_FROM_CLIENT+"\";filename=\"" + thumbnailName + "\"" + CRLF); ds.writeBytes(CRLF); //create thumbnail at new post activity result
String thumbnailFile = uploadFile.replace(".mp4","-thumbnail.jpg");
imageFis = new FileInputStream(thumbnailFile);
while ((length = imageFis.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(CRLF);
ds.writeBytes(twoHyphens + boundary + twoHyphens + CRLF); ds.flush();
} else if(Constant.IMAGE.equals(type)) {
newName = userId + "-image.jpg";//send image file
ds.writeBytes("Content-Disposition: form-data; " + "name=\""+Constant.FILE_KEY_IMAGE_FROM_CLIENT+"\";filename=\"" + newName + "\"" + CRLF);
ds.writeBytes(CRLF);
imageFis = new FileInputStream(uploadFile);
int length = -1;
while ((length = imageFis.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(CRLF);
ds.writeBytes(twoHyphens + boundary + twoHyphens + CRLF);
ds.flush();
}
}
<pre name="code" class="java">
</pre>
3. 如果在上传文件的同时还要上传多个参数:
可以在2中send normal param时的paramValue中写多个参数拼接的字符串, 在服务器端action中用如下代码获取该字符串, 再解析成多个参数及值.
MultiPartRequestWrapper request = (MultiPartRequestWrapper)ServletActionContext.getRequest();
String param = request.getParameter("param"); //data.type=image&post.description=I'm default description
但是使用这种方法就则没有使用到struts2的参数自动注入, 所以客户端要修改为如下, 封装addParam方法, 每个param都独立使用一次
Content-Disposition: form-data; name=specificKey ....
进行注入, 不要忘记打印边界值.
封装的addParam方法如下:
public static DataOutputStream addNormalParam(DataOutputStream ds, String paramKey, String paramValue){
try {
// Send normal param.
ds.writeBytes(twoHyphens + boundary + CRLF);
ds.writeBytes("Content-Disposition: form-data; name=\""+paramKey+"\""+CRLF);
ds.writeBytes("Content-Type: text/plain; charset=" + "UTF-8"+CRLF);
ds.writeBytes(CRLF+paramValue+CRLF);
ds.flush();
} catch (IOException e) {
e.printStackTrace();
}
return ds;
}
在client拼装请求时这样调用:
.... con.setChunkedStreamingMode(0);
/* 设置DataOutputStream */
ds = new DataOutputStream(con.getOutputStream());
// Send normal param.
HttpTool.addNormalParam(ds,"data.type",type);
ds.writeBytes(twoHyphens + boundary + CRLF);
HttpTool.addNormalParam(ds,"post.description",description);
ds.writeBytes(twoHyphens + boundary + CRLF);
....
则在服务端action的data及post成员会被自动注入值.