..我使用 apache lib 作为。
在我的线程 doInBackground() 方法中:
@Override
protected Object doInBackground(Object... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("photo", photosURLString));
LogMsg.d("Photo "+photosURLString);
if (loactionID != null){
nameValuePairs.add(new BasicNameValuePair("LocationID", loactionID));
LogMsg.d("teamID "+loactionID);
}
if (businessID != null){
nameValuePairs.add(new BasicNameValuePair("BusinessID", businessID));
LogMsg.d("BusinesID "+businessID);
}
nameValuePairs.add(new BasicNameValuePair("UserID", userID));
LogMsg.d("userID "+userID);
post(ActivityUploadPhotos.this.getString(R.string.image_upload), nameValuePairs);
return null;
}
这是post方法。
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("photo")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue()) ,"image/jpeg" ));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
LogMsg.d(""+response);
} catch (IOException e) {
e.printStackTrace();
}
}