一、PostMethod一般请求
/**
* POST方式
* @return
* @throws Exception
*/
public static String PostMethodTest() throws Exception{
System.out.println("开始");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(URI);
try{
method.addRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") );
method.addParameter(new NameValuePair("appid", "XXXX") );
method.addParameter(new NameValuePair("appkey", "XXXX") );
int result = client.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return URLDecoder.decode(baos.toString(), "UTF-8");
} else {
throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
}
}finally {
method.releaseConnection();
}
}
二、PostMethod带文件方式
/**
* POST方式 传带文件的调用
* @return
* @throws Exception
*/
public static String PostMethodFileTest() throws Exception{
System.out.println("开始");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(URI);
try{
FilePart filePart = new FilePart("file",new File("D:\\8\\5972-41-2017-06-07-1440-16406.wav"));
StringPart questionId = new StringPart("questionId","10001");
StringPart userId = new StringPart("userId","765709");
StringPart homeworkId = new StringPart("homeworkId","950");
Part[] parts ={filePart,questionId,userId,homeworkId};
MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams());
method.setRequestEntity(mre );
int result = client.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return URLDecoder.decode(baos.toString(), "UTF-8");
} else {
throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
}
}finally {
method.releaseConnection();
}
}