查看了很多资料。对方返回的是415,类型错误
应该使用Content-Type = "*/*"
/**
* 用于下载文件
* flag : 用于数据摆渡 , 输出流转换输入流 true为转换:::: 输出流转换输入流
为false写到文件中
*/
public static Map<String, Object> doPostDownLoad(String url, Map params, OutputStream fos, boolean flag) {
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setHeader("Content-Type", "*/*");
request.setURI(new URI(url));
//设置参数
request.setEntity(new StringEntity(FastJsonUtils.toJSONString(params)));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
Map<String, Object> mapResult = new HashMap<String, Object>();
mapResult.put("isSuccess", true);
if (flag) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
ByteArrayInputStream swapInputStream = new ByteArrayInputStream(bos.toByteArray());
mapResult.put("inputStream", swapInputStream);
} else {
response.getEntity().writeTo(fos);
}
return mapResult;
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
这段代码用于上传远程服务器
/**
* post请求(用于请求file传输)
* @param url
* @param instream
* @return
*/
public static String doPost(String url, InputStream instream) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/octet-stream");
httpPost.setHeader("Content-Type", "application/octet-stream");
String charSet = "UTF-8";
CloseableHttpResponse response = null;
httpPost.setEntity(new InputStreamEntity(instream));
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}