2013-04-06 4 views
0
myphp script on server side 

    <?php 



    // include db connect class 
    require_once __DIR__ . '/db_connect.php'; 

    // connecting to db 
    $db = new DB_CONNECT(); 

    $tvshowname = (isset($_POST['username']) ? $_POST['username'] : null); 


    $result=mysql_query("INSERT INTO test(imagename) VALUES ('$tvshowname')"); 


    $target_path1 = "http://" + "10.0.2.2/tvshow/tvshow_images/"; 



    //$target_path1 = "10.0.2.2/tvshow/tvshow_images/"; 

    //$target_path1 = 'http://10.0.2.2/tvshow/tvshow_images/'; 

    /* Add the original filename to our target path. 
    Result is "uploads/filename.extension" */ 
    $target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']); 
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) { 
     echo "The first file ". basename($_FILES['uploaded_file']['name']). 
     " has been uploaded."; 
    } else{ 
     echo "There was an error uploading the file, please try again!"; 
     echo "filename: " . basename($_FILES['uploaded_file']['name']); 
     echo "target_path: " .$target_path1; 
    } 




    ?> 


@SuppressWarnings("deprecation") 
     @Override 
     protected String doInBackground(String... f_url) { 



      HttpURLConnection connection = null; 
      DataOutputStream outputStream = null; 

      String pathToOurFile = UploadFilePath; 

      String urlServer = "http://" + "10.0.2.2" 
        + "/tvshow/upload_tvshows.php?username=" +"niranga"+""; 



      //"&tvshowchannel="+"sirasa tv"+"&tvshowtype=" 
      //+ "dailytelegrama" + "&tvshowdescription="+"nvnnnnnnnnnnn"; 



      String lineEnd = "\r\n"; 
      String twoHyphens = "--"; 
      String boundary = "*****"; 

      int bytesRead, bytesAvailable, bufferSize; 
      byte[] buffer; 
      int maxBufferSize = 1 * 1024 * 1024; 

      try { 
       FileInputStream fileInputStream = new FileInputStream(new File(

         pathToOurFile)); 

       URL url = new URL(urlServer); 
       connection = (HttpURLConnection) url.openConnection(); 



       // Allow Inputs & Outputs 
       connection.setDoInput(true); 
       connection.setDoOutput(true); 
       connection.setUseCaches(false); 




       // Enable POST method 
       connection.setRequestMethod("POST"); 

       //connection.setRequestProperty("username","niranga"); 








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

       outputStream = new DataOutputStream(
         connection.getOutputStream()); 
       outputStream.writeBytes(twoHyphens + boundary + lineEnd); 


       outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ pathToOurFile + "\"" +";username=\""+"niranga"+ lineEnd); 



       outputStream.writeBytes(lineEnd); 

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

       // Read file 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

       while (bytesRead > 0) { 
        for (int x = 0; x < 100; x++) { 
         // publishing the progress.... 
         // After this onProgressUpdate will be called 
         publishProgress("" + x); 
        } 
        outputStream.write(buffer, 0, bufferSize); 
        bytesAvailable = fileInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
       } 

       outputStream.writeBytes(lineEnd); 
       outputStream.writeBytes(twoHyphens + boundary + twoHyphens 
         + lineEnd); 

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

       //print server response here.. 
       Log.e("---------",(serverResponseCode + " ===> " 
         + serverResponseMessage)); 

       fileInputStream.close(); 
       outputStream.flush(); 
       outputStream.close(); 

      } catch (final Exception ex) { 

       runOnUiThread(new Runnable() { 
         public void run() { 

       AlertDialog alertDialog = new AlertDialog.Builder(
         AddTVShows.this).create(); 

       // Setting Dialog Title 
       alertDialog.setTitle("Alert Dialog"); 

       Log.e("Erorrr",ex.toString()); 

       // Setting Dialog Message 
       alertDialog.setMessage(ex.toString()); 


       // Setting OK Button 
       alertDialog.setButton("Upload Again", 
         new DialogInterface.OnClickListener() { 

          public void onClick(DialogInterface dialog, 
            int which) { 

           // Write your code here to execute after dialog 
           // closed 
           //Toast.makeText(getApplicationContext(), "", 
           //  Toast.LENGTH_SHORT).show(); 
          } 
         }); 

       // Showing Alert Message 
       alertDialog.show(); 

         } 
       }); 
      } 



      return null; 

     } 


i want to pass username parameter to serverside php script using HttpURLConnection.i use below url to do that .but username value not taking from server side php script.please help me to get username from server side php script.... 

я хочу отправленного значения имени пользователя на стороне сервера тобе PHP скрипт, вставленной database.but он вставлен нулевые значения ..как передать дату серверу с помощью HttpURLConnection?

Строка urlServer = "HTTP: //" + "10.0.2.2" + " /tvshow/upload_tvshows.php?username= "+" niranga "+" ";

ответ

0

http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html

Вам необходим запрос HTTP POST замыкающего к ссылке. Также вы должны использовать Asyntask

public void postData() { 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 

} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 
} 
Смежные вопросы