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

时间:2022-10-29 14:28:49

I am trying to upload video to server,but whenever I am trying to upload response is showing null null and in logcat it shows org.json.JSONException: End of input at character 0 of,instead of my response status:success msg:video uploaded..can any body tell me what is my mistake? org.json.JSONException:字符0的输入结束

我正在尝试将视频上传到服务器,但每当我尝试上传响应时显示null null并且在logcat中它显示org.json.JSONException:输入结束于字符0,而不是我的响应状态:success msg:video upload..can任何身体告诉我我的错误是什么?

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 个解决方案

#1


4  

Try to use BufferedReader :

尝试使用BufferedReader:

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

#2


5  

You are getting the org.json.JSON Exception : End of input at character 0 Because, you got null response which generated that exception.

您正在获取org.json.JSON异常:字符0处的输入结束因为,您获得了生成该异常的空响应。

So, Check your result string before convert in to JSONObject.

因此,在转换为JSONObject之前检查结果字符串。

JSONObject jobj = new JSONObject(result); // Check this result string.

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

Again answer for Request.

再次回答请求。

Haresh Chhelana Answer is correct.

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());

Thanks.

#1


4  

Try to use BufferedReader :

尝试使用BufferedReader:

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

#2


5  

You are getting the org.json.JSON Exception : End of input at character 0 Because, you got null response which generated that exception.

您正在获取org.json.JSON异常:字符0处的输入结束因为,您获得了生成该异常的空响应。

So, Check your result string before convert in to JSONObject.

因此,在转换为JSONObject之前检查结果字符串。

JSONObject jobj = new JSONObject(result); // Check this result string.

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

Again answer for Request.

再次回答请求。

Haresh Chhelana Answer is correct.

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());

Thanks.