2011-02-09 33 views
2

我此刻的1 2種方法來發布文件,另一張貼一些文字,它們低於Android的後處理文件和文本

後的數據...

public void postData() { 
    // Create a new HttpClient and Post Header 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    EditText et = (EditText) findViewById(R.id.entry); 
    String enteredName = et.getText().toString(); 
    gender(); 
    category(); 
    nameValuePairs.add(new BasicNameValuePair("name",enteredName)); 
    nameValuePairs.add(new BasicNameValuePair("gender",radio)); 
    nameValuePairs.add(new BasicNameValuePair("cat",radio2)); 

    //http post 
    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://10.0.2.2:90/upload.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block  
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 


       } 

發佈文件...

public void postFile(){ 
    File file = new File(filedir2); 
    try { 
      System.out.println(filedir2); 
      HttpClient client = new DefaultHttpClient(); 
      String postURL = "http://10.0.2.2:90/mobileupload.php";     
      HttpPost post = new HttpPost(postURL); 


     FileBody bin = new FileBody(file); 
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     reqEntity.addPart("image", bin); 
     post.setEntity(reqEntity); 
     HttpResponse response = client.execute(post); 
     HttpEntity resEntity = response.getEntity(); 
     if (resEntity != null) {  
        Log.i("RESPONSE",EntityUtils.toString(resEntity)); 
      } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

我已經提出,結合了mobileupload.php和upload.php的一個PHP文件,我只是想知道是否有辦法我能得到這個成一個方法,只是做一個帖子?

幫助,將不勝感激

感謝

詹姆斯

回答

2

您可以使用這樣的事情:

File file = new File("FileToSend.txt"); 
HttpClient client = new HttpClient(); 

String url = "http://www.yourdomain.com/destination.php"; 
PostMethod postMethod = new PostMethod(url); 

Part[] parts = {new FilePart(file.getName(), file)}; 
postMethod.setParameter("name", "value"); // set parameters like this instead in separate call 

postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); 

int status = client.executeMethod(postMethod); 
+1

它不承認HttpClient的命令,我已經包括3.0.1罐子文件。任何想法爲什麼,它確實需要HttpDefaultClient,但不起作用 – user606669 2011-09-14 23:11:14