数据未通过POST从Android发送到Servlet

时间:2014-11-14 06:18:08

标签: android servlets post

我有一个Android应用程序,我需要使用POST multipart / form-data将图像文件发送到servlet。问题是正在调用servlet并且在Android手机上收到响应。但是没有数据在服务器端收到。不仅是图像,还有其他数据,如标题'和'描述'同样。

有人可以告诉我问题在哪里吗?

Android代码:

public String Sending(){
        String iFileName = "card.png";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="fSnd";
        String s = null;
        try
        {

                HttpFileUpload hfu = new HttpFileUpload("http://192.168.2.48:8080/ImagePreprocessing/PreprocessingPath", "image","Image to be preprocessed");
                Log.e(Tag,"Starting Http File Sending to URL");

                // Open a HTTP connection to the URL
                HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");

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

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(Title);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);

                dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(Description);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);

                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                dos.writeBytes(lineEnd);

                Log.e(Tag,"Headers are written");

                // create a buffer of maximum size
                int bytesAvailable = fileInputStream.available();

                int maxBufferSize = 1024;
                int bufferSize = Math.min(bytesAvailable, maxBufferSize);
                byte[ ] buffer = new byte[bufferSize];

                // read file and write it into form...
                int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable,maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,bufferSize);
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // close streams
                fileInputStream.close();

                dos.flush();

                Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                InputStream is = conn.getInputStream();

                // retrieve the response from server
                int ch;

                StringBuffer b =new StringBuffer();

                while( ( ch = is.read() ) != -1 ) { 
                    b.append( (char)ch ); 
                }

                s=b.toString();
                Log.i("Response",s);
                dos.close();

        }

        catch (MalformedURLException ex)
        {
                Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
                Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
        return s;
}

Servlet代码:

@WebServlet("/PreprocessingPath")
public class Preprocessing extends HttpServlet {
 private static final long serialVersionUID = 1L;


public Preprocessing() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}

   /**
 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
 */
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String method = request.getMethod();

       doPost(request, response);
}


/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Hi from Post");

    // get current date time with Date()
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                
    Date date = new Date();
    String timestamp = dateFormat.format(date);

    // set the filename
    String filename = "IMAGE_" + timestamp +".png";

    String title = request.getParameter("title");

    String description = request.getParameter("description");

    System.out.println("Title: "+ title);
    System.out.println("Description: "+ description);

    PrintWriter writer = response.getWriter();
    writer.println("Server says hello !");  

    byte[] byteArray = request.getParameter("filename").getBytes();

    // save the image file on the server
    FileOutputStream fos = new FileOutputStream("C:/Users/NAPSTER/ADT/ImagePreprocessing/WebContent/WEB-INF/"+filename);
    try {
        fos.write(byteArray);
    }
    finally {
        fos.close();
    }

    PreProcessingTest.startPreprocessing(filename);
}   

}

控制台:

Hi from Post
Title: null
Description: null
Nov 14, 2014 1:06:15 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.patternrecognition.preprocessing.Preprocessing] in context with path     [/ImagePreprocessing] threw exception
 java.lang.NullPointerException
at com.patternrecognition.preprocessing.Preprocessing.doPost(Preprocessing.java:84)
at com.patternrecognition.preprocessing.Preprocessing.service(Preprocessing.java:56)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

logcat的:

enter image description here

1 个答案:

答案 0 :(得分:0)

步骤1:创建一个向servlet创建请求的方法。

    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

private static HttpClient mHttpClient;

private static HttpClient getHttpClient() {

    if (mHttpClient == null) {

        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}
    public static String postUrl(String url, List<NameValuePair> nameValuePairs)
        throws Exception {

    InputStream is = null;
    BufferedReader in = null;
    String result = "";
    try {

        HttpPost httpost = new HttpPost(url);
        HttpClient client = getHttpClient();

        httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(httpost);

        HttpEntity resEntity = response.getEntity();

        is = resEntity.getContent();
        in = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
                1024 * 4);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        result = sb.toString();

    } catch (Exception e) {
        Log.wtf("Exception", "Exception: " + e.toString());
    } finally {
        in.close();

    }

    return result;

}

第2步:你要发送什么,将它添加到List中并在asynctask构造函数中传递

List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams
                .add(new BasicNameValuePair("KEY", "VALUE")));
SendData mSendData = new SendData(URL,
                postParams);
        mSendData .execute();

第3步:创建一个asynctask来发送数据

public class SendData extends AsyncTask<String, String, String> {


String mUrl;
List<NameValuePair> postParams;

public SendLatLong(String URL, List<NameValuePair> postParams) {
    this.mUrl = URL;
    this.postParams = postParams;
}

@Override
protected String doInBackground(String... params) {
    try {
        //call that method (postURL) and pass the url of the servlet and namevaluepair
        postUrl(mUrl, postParams);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}

随意恢复任何查询。