org.json.JSONException:字符0的输入结束

时间:2014-12-31 04:18:03

标签: android json android-videoview

我正在尝试将视频上传到服务器,但每当我尝试上传响应时显示null null,而在logcat中它显示org.json.JSONException:输入结束时的字符0,而不是我的响应状态:success msg:视频已上传..任何人都可以告诉我,我的错误是什么? enter image description here

public class VideoUpload extends Activity{

MediaController mc;

 private static int SELECT_PICTURE = 1;  
 private String selectedImagePath="";  
 TextView messageText;  
 Button uploadButton;  
 int serverResponseCode = 0;  
 ProgressDialog dialog = null;  

 private static final String TAG_SUCCESS = "status";  
 private static final String TAG_MSG = "msg";  

 String imgs;  
 String btns;  

 String upLoadServerUri = null;  

 ThreadPolicy th = new ThreadPolicy.Builder().permitAll().build();  

 final String uploadFilePath =  Environment.getExternalStorageDirectory().getPath();  

  private Button buttonLoadImage;  
  private VideoView img;  

  private String User_ID;  
  private String sta;  
  private String msg;  
  private HttpURLConnection conn = null;  
  private  String result="";  

  @Override  
   public void onCreate(Bundle savedInstanceState) {  

   super.onCreate(savedInstanceState);
   setContentView(R.layout.layout_video);

   StrictMode.setThreadPolicy(th);
   User_ID=this.getIntent().getStringExtra("id");
   System.out.println("photo upload user id"+User_ID);

   img = (VideoView)findViewById(R.id.imgViewvid);

   mc = new MediaController(this);
   mc.setAnchorView(img);

   buttonLoadImage = (Button) findViewById(R.id.buttonLoadvid);
   buttonLoadImage.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View arg0) {

            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);

       }
   });
   uploadButton = (Button)findViewById(R.id.uploadButtonvid);
   messageText  = (TextView)findViewById(R.id.messageTextvid);

    uploadButton.setOnClickListener(new OnClickListener() {            
       @Override
       public void onClick(View v) {

           dialog = ProgressDialog.show(VideoUpload.this, "", "Uploading file...", true);

           new Thread(new Runnable() {
                   public void run() {
                        runOnUiThread(new Runnable() {
                               public void run() {
                                messageText.setText("uploading started.....");
                               }
                           });                      

                        uploadFile(selectedImagePath);

                   }
                 }).start();        
           }
       });
   }


 @Override  
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) 
   {
       if (requestCode == SELECT_PICTURE) 
       {

           Uri mVideoURI = data.getData();
           selectedImagePath = getPath(mVideoURI);

           messageText.setText(selectedImagePath);
           System.out.println(requestCode);
           System.out.println("Image Path : " + selectedImagePath);

           img.setVideoURI(mVideoURI);  

      }
   }
  }  

  @SuppressWarnings("deprecation")
  public String getPath(Uri uri) {
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = managedQuery(uri, projection, null, null, null);
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   cursor.moveToFirst();
   return cursor.getString(column_index);
 }

public int uploadFile(String sourceFileUri) {


     DataOutputStream dos = null;  
     String lineEnd = "\r\n";
     String twoHyphens = "--";
     String boundary = "*****";
     int bytesRead, bytesAvailable, bufferSize;
     byte[] buffer;
     int maxBufferSize = 1 * 1024 * 1024; 
     File sourceFile = new File(sourceFileUri); 


     if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                               + selectedImagePath);


           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           + selectedImagePath);
               }
           }); 

           return 0;
     }
     else
     {
           try { 
                  btns=uploadButton.getTag().toString();
                System.out.println(btns);
                  String fileName = sourceFileUri;
                  File f  = new File(selectedImagePath);
                 imgs= f.getName();
                System.out.println(imgs);

                upLoadServerUri = "http://mywebsitename.com/webservice/addvideo?version=apps&user_login_id="+User_ID+"&video_1="+imgs+"&action="+btns;



               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);
               System.out.println(url);

               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");

                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("video_1", imgs);
                   conn.setRequestProperty("user_login_id", User_ID);
                   conn.setRequestProperty("action", btns);
                   conn.setRequestProperty("version", "apps");


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


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

                 // assign value
                 dos.writeBytes("version=apps");
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + lineEnd);

                 dos.writeBytes("user_login_id="+User_ID);
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + lineEnd);

                 dos.writeBytes("action="+btns);
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + lineEnd);

                 // send image
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name='video_1';filename='"
                         + imgs + "'" + lineEnd);

                 dos.writeBytes(lineEnd);

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

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

               // read file and write it into form...
               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);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.i("uploadFile", "HTTP Response is : " 
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        @SuppressWarnings("deprecation")
                        public void run() {


                            try 
                            {

                                DataInputStream dataIn = new DataInputStream(conn.getInputStream());
                                String inputLine;
                                while ((inputLine = dataIn.readLine()) != null) 
                                {
                                    result += inputLine;
                                    System.out.println("Result : " + result);
                                }
                                JSONObject jobj = new JSONObject(result);
                                sta = jobj.getString("status");
                                msg = jobj.getString("msg");

                                System.out.println(sta + " >>>>>>> " + msg);
                            } 
                            catch (Exception e) 
                            {
                                e.printStackTrace();
                            }


                            Toast.makeText(VideoUpload.this, "" + sta + " : " + msg, 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(VideoUpload.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(VideoUpload.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }


          dialog.dismiss();       
          return serverResponseCode; 

      } // End else block 

    } 

2 个答案:

答案 0 :(得分:5)

您正在获取org.json.JSON Exception : End of input at character 0因为,您获得了生成该异常的空响应。

所以,Check your result string before convert in to JSONObject.

  

JSONObject jobj = new JSONObject( result ); //检查此结果字符串。

再次回答请求。

Haresh Chhelana答案是正确的。

BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
    result.append(line);
}
JSONObject jobj = new JSONObject(result.toString());

感谢。

答案 1 :(得分:4)

尝试使用BufferedReader:

BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
    result.append(line);
}