如何编写客户端以从 Rest Web 服务获取数据和图像文件



我写了一个java REST Web服务,它接受我在标头参数中发送的图像文件和json数据,所以我想知道如何编写客户端来成功调用该Web服务。我的问题是如何在标头参数中传递图像文件和 json 数据以调用该网络服务。我如何在请求中设置图像.请在下面找到我必须公开的 REST Web 服务代码。

@Path("/KVBSvasth")
public class KvbSvasthWebServices {


private static final String FILE_UPLOAD_PATH = "D:\home"; 

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/getKvbMemberDetails")
public String saveClaimSubmissionMultiplePdf(@Context HttpServletRequest request,@HeaderParam("jsondataaa")String jsondata) throws Exception
{

WebServiceManager webServiceManager=null;
try{
KvbSvasthVO kvbSvasthVO=null;
String msg="";
String enrollmentID="";
System.out.println("json Data get "+jsondata);

//try{
ObjectMapper mapper = new ObjectMapper();
kvbSvasthVO= mapper.readValue(jsondata, KvbSvasthVO.class);
//}catch(JsonParseException | JsonMappingException jsonexception){
//  msg="Data parsing exception";
//return this.getJsonOutputString(msg, enrollmentID);
//}
if (ServletFileUpload.isMultipartContent(request)) {
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
final List items = fileUpload.parseRequest(request);
if(items.size()>0){
if (items != null) {
System.out.println("its should 2");
final Iterator iter = items.iterator();
while (iter.hasNext()) {
System.out.println("its should 3");
final FileItem item = (FileItem) iter.next();
final String itemName = item.getName();
item.getFieldName();
item.getString();
String strFileExt = itemName.substring(itemName.lastIndexOf(".") + 1,itemName.length());
File folder = new File(FILE_UPLOAD_PATH);
webServiceManager=this.getWebServiceManagerObject();

//kvbSvasthVO.setFileDataOInputStream(item.getInputStream());
//  kvbSvasthVO.setImageFileSize((int)item.getSize());
//kvbSvasthVO.setJsonData(jsondata);
webServiceManager.saveKvbSvasthCustDetails(kvbSvasthVO,item,jsondata);

if (!folder.exists()) {
System.out.println("its should 4");
folder.mkdir();
} // End Of if(!folder.exists())
if (!(strFileExt.equalsIgnoreCase("pdf"))) {   
final File savedFile = new File(FILE_UPLOAD_PATH+ File.separator + itemName);
System.out.println("final file "+FILE_UPLOAD_PATH+ File.separator + itemName);
item.write(savedFile);
} 

break;
}//end of while (iter.hasNext())
} // end of if (items != null) 
}//end of if(items.size()>0)

}
}catch(Exception e){
System.out.println("exception occurs: ");
e.printStackTrace();
}
return jsondata;
}

public String getJsonOutputString(String message,String enrollementID){
JSONObject jsobj = new JSONObject();
LinkedHashMap<String, String> object = new LinkedHashMap();
//object.put("status", status);
object.put("msg",message);
object.put("enrollemntId",enrollementID);
jsobj.putAll(object);
return jsobj.toJSONString();
}

private WebServiceManager getWebServiceManagerObject() throws TTKException
{
WebServiceManager webServiceManager = null;
try
{
if(webServiceManager == null)
{
InitialContext ctx = new InitialContext();
webServiceManager = (WebServiceManager) ctx.lookup("java:global/TTKServices/business.ejb3/WebServiceManagerBean!com.ttk.business.webservice.WebServiceManager");
}//end if(webServiceManager == null)
}//end of try
catch(Exception exp)
{
throw new TTKException(exp, "webservice");
}//end of catch
return webServiceManager;
}//end getWebServiceManagerObject()
}

请帮忙,谢谢。

使用 header 传递 json 数据不是最佳做法 - 它们应该转到正文。但是,让我们假设您有一个很好的理由。 为了传递图像,您需要先将其转换为字节数组。 以下是如何在 java 中设置标头值的示例:

HttpClient httpClient = HttpClients.createDefault()
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("jsondataaa", headerData);
HttpEntity requestEntity = new ByteArrayEntity(requestContent);
Path path = Paths.get("path/to/file"); 
byte[] data =  Files.readAllBytes(path); 
HttpEntity requestEntity = new ByteArrayEntity(data); 
httpPost.setEntity(requestEntity);
logXmlRequestResponse(requestContent, operationType + " Request");
HttpResponse execute = httpClient.execute(httpPost);
httpPost.releaseConnection();

好的,我很喜欢.下面的客户端代码工作正常。

package client;
import java.io.File;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class RESTClient {
public static void main(String args[]) throws Exception {
File f = new File("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
sendFile(f);
}
public static void sendFile(File file) throws Exception 
{
String BASE_URL="http://10.1.4.126:8080/rest/KVBSvasth/getKvbMemberDetails";
HttpClient client = new DefaultHttpClient() ;
HttpPost postRequest = new HttpPost (BASE_URL) ;
try
{
//Set various attributes 
MultipartEntity multiPartEntity = new MultipartEntity() ;
// multiPartEntity.addPart("fileName", new StringBody(file.getName() != null ? file.getName() : file.getName())) ;
FileBody fileBody = new FileBody(file) ;
//Prepare payload
multiPartEntity.addPart("attachment", fileBody) ;
//Set to request body
postRequest.setEntity(multiPartEntity) ;
Scanner sc = new Scanner(new File("C:/Users/rishabh.keshari/Desktop/json.txt"));
postRequest.setHeader("jsondataaa",sc.nextLine());
//Send request
HttpResponse response = client.execute(postRequest) ;
//Verify response if any
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch (Exception ex)
{
ex.printStackTrace() ;
}
}
}

相关内容

  • 没有找到相关文章

最新更新