android和servlet之间的通信

时间:2012-02-28 05:29:42

标签: java android servlets

我制作了用于存储html文件的servlet。

是否可以使用该servlet从android代码保存我的文件..

我的servlet如下

 public class UploadImage extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println("request: "+request);
    if (!isMultipart) {
        System.out.println("File Not Uploaded");
    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;

        try {
            items = upload.parseRequest(request);
            System.out.println("items: "+items);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()){
                String name = item.getFieldName();
                System.out.println("name: "+name);
                String value = item.getString();
                System.out.println("value: "+value);
            } else {
                try {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";
                    System.out.println("Text before replacing is:-" + itemName);
                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf("."); 
                    String domainName = itemName.substring(IndexOf);
                    System.out.println("domainName: "+domainName);

                    String finalimage = buffer.toString()+"_"+r+domainName;
                    finalimage=finalimage.substring(finalimage.lastIndexOf("\\")+1,finalimage.length());

                    System.out.println("Final Image==="+finalimage);






                    File savedFile = new File(finalimage);
                    item.write(savedFile);
                    FileInputStream in=new FileInputStream(savedFile);


                    Connection conn = null;
                    String url = "jdbc:mysql://localhost:3306/";
                    String dbName = "test";
                    String driver = "com.mysql.jdbc.Driver";
                    String username = "root"; 
                    String userPassword = "admin";
                    String strQuery = null;
                    String strQuery1 = null;
                    String imgLen="";

                    try {
                        System.out.println("itemName::::: "+itemName);
                        Class.forName(driver).newInstance();
                        conn = DriverManager.getConnection(url+dbName,username,userPassword);


                        PreparedStatement stmt=conn.prepareStatement("insert into testimage(image) values(?)");


                        stmt.setBinaryStream(1,in,in.available()+2);
                        stmt.executeUpdate();
                        stmt.close(); 


                        System.out.println("Query Executed Successfully++++++++++++++");
                        out.println("image inserted successfully");
                        out.println("</body>");
                        out.println("</html>");                     
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    } finally {
                        conn.close();
                    }       
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

}

我知道这样的事情......但不确定。

HttpURLConnection  conn = (HttpURLConnection) url.openConnection(); 

            conn.setDoInput(true); 

            conn.setDoOutput(true); 

            conn.setUseCaches(false); 

            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

jar或执行此任务

你的回复对我很有帮助..

2 个答案:

答案 0 :(得分:0)

您可以使用apache Http Components和mime4j将multipart发送到您的servlet 看这个例子

        InputStream inputStream = this.getAssets().open("image.png");

        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://10.10.10.144:8080/TestingApacheHttpClients/PostGetServletTest");


        byte[] data = IOUtils.toByteArray(inputStream);//from apache commons IO

        InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), "uploadedFile");
        StringBody sb1 = new StringBody("Nammaeri 101");
        StringBody sb2 = new StringBody("this is tamara");

        MultipartEntity multipartEntity = new MultipartEntity();

        multipartEntity.addPart("fileUploaded", isb);
        multipartEntity.addPart("parmaeter1", sb1);
        multipartEntity.addPart("parameter2", sb2);

        request.setEntity(multipartEntity);
            HttpResponse response = client.execute(request);

答案 1 :(得分:0)

customhttpclient.java位于此链接customhttpclient.java

在项目中使用它,然后以下列方式从servlet访问

ArrayList<NameValuePair> postdates = new ArrayList<NameValuePair>();
            postdates.add(new BasicNameValuePair("accountno",selected_accountno));
            postdates.add(new BasicNameValuePair("fromdate", fromdate));
            postdates.add(new BasicNameValuePair("todate", todate));

            try {

            String response = CustomHttpClient.executeHttpPost("http://"+server_ip+":8080/AndroidResponse/ICICIGetAccountStatement", postdates);
            resp = response.toString();
            resp = resp.replaceAll("\\s+","");
            //System.out.println("Resp from Server: "+ resp);

            } catch (Exception e) {
            //System.out.println("Error at after server response :"+e.toString());
            }