我使用如下的HttpURLConnection上传文件:
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String UploadURLPath = "upload php path";
URL url = new URL(UploadURLPath);
CameraUploadConnection = (HttpURLConnection) url.openConnection();
CameraUploadConnection.setDoInput(true);
CameraUploadConnection.setDoOutput(true);
CameraUploadConnection.setUseCaches(false);
CameraUploadConnection.setRequestMethod("POST");
CameraUploadConnection.setRequestProperty("Connection", "Keep-Alive");
CameraUploadConnection.setRequestProperty("Accept", "text/*");
CameraUploadConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(CameraUploadConnection.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end);
ds.write(SavePath.getBytes("UTF-8"));
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\"");
ds.write(FileName.getBytes("UTF-8"));
ds.writeBytes("\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(Path);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
ds.flush();
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
它可以上传,但存在一些问题 所以我想修改为PostMethod和HttpClient进行上传 我该如何修改它?
答案 0 :(得分:2)
以下是使用httpclient和httppost方法的示例
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
long timeout = 6000;
HttpConnectionParams.setConnectionTimeout(httpParameters, (int) timeout);
httpclient.setParams(httpParameters);
HttpPost httpPost = new HttpPost(licensingUrl);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
String stringData = "{\"data\":\"to send\"}";
try
{
httpPost.setEntity(new StringEntity(string Data));
}
catch (UnsupportedEncodingException e)
{
Log.d("Licensing", e.toString());
}
try
{
HttpResponse response = httpclient.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
答案 1 :(得分:1)
我可以给你一个示例课程。看看是否有帮助。
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc)
{
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
String Send_Now(FileInputStream fStream)
{
fileInputStream = fStream;
String server_response=Sending();
return server_response;
}
String Sending(){
String iFileName = Title;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
String res;
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
//conn.setDoOutput(true);
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024*1024*100;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
res=b.toString();
Log.i("Response-->",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
res="-1";
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
res="-1";
}
return res;
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}