2017-07-19 50 views
0

我想發送一個簡單的POST命令來上傳文件。我如何在android開發人員編寫代碼?代碼應提供以下POST請求請給出非常簡單的基本POST命令代碼android studio

POST /macros/s/AqtUErjtk/postform?no&func=uploadFiles HTTP/1.1 
Host: xyz.website.com 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-US,en;q=0.5 
Accept-Encoding: gzip, deflate, br 
Content-Type: multipart/form-data; boundary=---------------------------236532717524914 
Content-Length: 337 

的Cookie:

NID=106=gWQeUVIa2phdDJeXYdRFSPTnsklPrFVRwphw3G685QYZlDiZz7NK5PoJVEd1FYL6IqYoJ9fEtVHf0sKBIHq1wD1xr 
Connection: close 
Upgrade-Insecure-Requests: 1 


-----------------------------236532717524914 
Content-Disposition: form-data; name="_1_myFile"; filename="textfile.txt" 
Content-Type: text/plain 

這裏是文本文件內容yoyoyoyoyoy ------------------- ---------- 236532717524914--

+0

看看這個鏈接可以幫助你:https://community.particle.io/t/example-android-application-post-get/9355 – Dalton

+0

非常感謝! – user8334568

+0

你有成功嗎? :) – Dalton

回答

0

下面的鏈接,你會看到,其中POST是做出了表率:

https://community.particle.io/t/example-android-application-post-get/9355

這是從上面的鏈接提取的確切代碼:

class PostClient extends AsyncTask<String, Void, String> { 
     public String doInBackground(String... IO) { 

      // Predefine variables 
      String io = new String(IO[0]); 
      URL url; 

      try { 
       // Stuff variables 
       url = new URL("https://api.spark.io/v1/devices/YOURCOREID/SCL/"); 
       String param = "access_token=YOURACCESSTOKEN&params=d7,"+io; 
       Log.d(TAG, "param:" + param); 

       // Open a connection using HttpURLConnection 
       HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 

       con.setReadTimeout(7000); 
       con.setConnectTimeout(7000); 
       con.setDoOutput(true); 
       con.setDoInput(true); 
       con.setInstanceFollowRedirects(false); 
       con.setRequestMethod("POST"); 
       con.setFixedLengthStreamingMode(param.getBytes().length); 
       con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

       // Send 
       PrintWriter out = new PrintWriter(con.getOutputStream()); 
       out.print(param); 
       out.close(); 

       con.connect(); 

       BufferedReader in = null; 
       if (con.getResponseCode() != 200) { 
        in = new BufferedReader(new InputStreamReader(con.getErrorStream())); 
        Log.d(TAG, "!=200: " + in); 
       } else { 
        in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
        Log.d(TAG, "POST request send successful: " + in); 
       }; 


      } catch (Exception e) { 
       Log.d(TAG, "Exception"); 
       e.printStackTrace(); 
       return null; 
      } 
      // Set null and we´e good to go 
      return null; 
     } 
    } 
} 

我希望它能幫助。