你先得确定服务器用什么协议啊,HTTP,webservice,socket等等,如果用http一般两种方式,一个是java自带的urlhttpconnection,还有就是阿帕奇的httpclient。

代码片段

// 使用POST方法提交数据,必须大写

conn.setRequestMethod(POST);

// 需要输出流

conn.setDoOutput(true);

// 需要输入流

conn.setDoInput(true);

// 连接超时,10秒

conn.setConnectTimeout(10 * 1000);

// 读取超时,10秒

conn.setReadTimeout(10 * 1000);

// 打开输出流,写入数据

out = conn.getOutputStream();

out.write(data);

out.flush();

// 以上

conn.connect();

if (conn.getResponseCode() == 200) {

in = conn.getInputStream();

// TODO 读取数据

// 参考

int contentLength = conn.getContentLength();

ByteArrayOutputStream buf = new ByteArrayOutputStream(

contentLength 0 ? contentLength : 1024);

byte[] buffer = new byte[1024];

while ((contentLength = in.read(buffer)) != -1) {

buf.write(buffer, 0, contentLength);

}

// 可选

buf.flush();

return buf.toByteArray();

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (out != null) {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (conn != null) {

conn.disconnect();

}

// 错误的写法

// try {

// in.close();

// out.close();

// } catch (IOException e) {

// // TODO Auto-generated catch block

// e.printStackTrace();

// }

}

//尽量不要返回null 避免空指针异常

return new byte[0];

}

服务器在getpost里面接收可以转为btye数组,然后在转为文件

取消

评论

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐