Created
April 13, 2015 07:00
-
-
Save suanmiao/170c57498e0df532eb34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static ResponseHolder httpUploadFile(String targetUrl, | |
String filePath, ArrayList<NameValuePair> headerArrayList, | |
ArrayList<NameValuePair> paramsArrayList) { | |
// about url | |
for (int i = 0; i < paramsArrayList.size(); i++) { | |
NameValuePair nowPair = paramsArrayList.get(i); | |
if (i == 0) { | |
targetUrl += ("?" + nowPair.getName() + "=" + nowPair | |
.getValue()); | |
} else { | |
targetUrl += ("&" + nowPair.getName() + "=" + nowPair | |
.getValue()); | |
} | |
} | |
/* 建立HTTP Post联机 */ | |
HttpPost httpRequest = new HttpPost(targetUrl); | |
/* | |
* Post运作传送变量必须用NameValuePair[]数组储存 | |
*/ | |
try { | |
// set entity | |
MultipartEntity multipartEntity = new MultipartEntity(); | |
File uploadFile = new File(filePath); | |
FileBody fileBody = new FileBody(uploadFile); | |
String fileName = uploadFile.getName(); | |
Log.e("upload file name", "" + fileName); | |
multipartEntity.addPart("Filename", new StringBody(fileName)); | |
multipartEntity.addPart("folder", | |
new StringBody("/cgi-bin/uploads")); | |
multipartEntity.addPart("file", fileBody); | |
multipartEntity.addPart("Upload", new StringBody("Submit Query")); | |
httpRequest.setEntity(multipartEntity); | |
for (int i = 0; i < headerArrayList.size(); i++) { | |
httpRequest.addHeader(headerArrayList.get(i).getName(), | |
headerArrayList.get(i).getValue()); | |
} | |
HttpParams httpParams = new BasicHttpParams(); | |
HttpConnectionParams.setConnectionTimeout(httpParams, 100000); | |
HttpConnectionParams.setSoTimeout(httpParams, 30000); | |
HttpClient httpClient = new DefaultHttpClient(httpParams); | |
/* 取得HTTP response */ | |
HttpResponse httpResponse = httpClient.execute(httpRequest); | |
/* 若状态码为200 ok */ | |
if (httpResponse.getStatusLine().getStatusCode() == 200) { | |
/* 取出响应字符串 */ | |
return new ResponseHolder(ResponseHolder.RESPONSE_TYPE_OK, | |
httpResponse); | |
} else { | |
Log.e("errorcode", httpResponse.getStatusLine().toString()); | |
} | |
} catch (ClientProtocolException e) { | |
Log.e("upload client pro", "" + e); | |
e.printStackTrace(); | |
} catch (IOException e) { | |
Log.e("upload io", "" + e); | |
e.printStackTrace(); | |
if (e instanceof SocketTimeoutException | |
|| e instanceof javax.net.ssl.SSLPeerUnverifiedException) { | |
return new ResponseHolder( | |
ResponseHolder.RESPONSE_TYPE_ERROR_TIME_OUT, null); | |
} | |
} catch (Exception e) { | |
Log.e("upload ex", "" + e); | |
e.printStackTrace(); | |
} | |
return new ResponseHolder(ResponseHolder.RESPONSE_TYPE_ERROR_OTHER, | |
null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment