我想发送一个简单的POST命令来上传文件。如何在android开发人员中编写代码?代码应该提供以下POST请求
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 :(得分: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¶ms=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;
}
}
}
我希望它有所帮助。