Kel*_*lib 28 parameters post android file
我需要将一些数据上传到PHP服务器.我可以用参数发帖:
String url = "http://yourserver";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
}
Run Code Online (Sandbox Code Playgroud)
我也可以上传文件:
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
}
Run Code Online (Sandbox Code Playgroud)
但是我怎么把它放在一起呢?我需要在一个帖子中上传图片和参数.谢谢
Mar*_* S. 12
您必须使用MultipartEntity.在线查找并下载这两个库:httpmime-4.0.jar和apache-mime4j-0.4.jar然后你可以根据需要附加任意数量的东西.以下是如何使用它的示例:
HttpPost httpost = new HttpPost("URL_WHERE_TO_UPLOAD");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myString", new StringBody("STRING_VALUE"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Run Code Online (Sandbox Code Playgroud)
对于服务器端,您可以使用这些实体标识符名称myImageFile,myString以及myAudioFile.
| 归档时间: |
|
| 查看次数: |
33636 次 |
| 最近记录: |