我想发送一个文件到webservice,但我需要发送更多的信息,所以我想用json发送它们.但是当我把一个文件放在我的jsonObject中时,我得到一个错误,说它不是一个字符串.我的问题是,我应该拿我的文件并转换为字符串,然后放入我的json和Web服务中取出它并将该字符串转换为文件?还是有另一种简单的方法吗?
这是我的代码:
客户:
private void send() throws JSONException{
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource("http://localhost:8080/proj/rest/file/upload_json");
JSONObject my_data = new JSONObject();
File file_upload = new File("C:/hi.txt");
my_data.put("User", "Beth");
my_data.put("Date", "22-07-2013");
my_data.put("File", file_upload);
ClientResponse client_response = service.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, my_data);
System.out.println("Status: "+client_response.getStatus());
client.destroy();
}
Run Code Online (Sandbox Code Playgroud)
网络服务
@POST
@Path("/upload_json")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("text/plain")
public String receive(JSONObject json) throws JSONException {
//Here I'll save my file and make antoher things..
return "ok";
}
Run Code Online (Sandbox Code Playgroud)
在所有答案之后,这是我的代码 - 谢谢大家:
网络服务
import java.io.File;
import java.io.FileOutputStream; …Run Code Online (Sandbox Code Playgroud)