我试图将图像上传到服务器以及一个从形式收集了一些JSON数据。
该服务器的身份验证。
方法:交
头:
授权基本d2Vic2VydmljZTpyM05hdTE3Rw ==
内容类型的multipart / form-data的;边界= XXXXXXXX
体:
--xxxxxxxx
内容处置:表格数据; NAME =jsonFile
内容类型:应用程序/ JSON
{"model":"$p$pmium","deviceLongitude":4.79337638,"pseudo":"nickname","deviceLatitude":45.7671507,"year":"2005","email":"email@mail.com","deviceLocale":"fr_FR","title":"my图片}
--xxxxxxxx
内容处置:表格数据; NAME =imgName
内容类型:图像/ JPEG
//图像数据阵列
/ 9J / 4AAQSkZJRgABAQAAAQABAAD / 4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAAB
AAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAB4KAD
AAQAAAABAAACgAAAAAD / 2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH / 2wBDAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQH / wAARCAKAAeADAREAAhEBAxEB / 8QAHwAAAQUBAQEBAQEAAAAAAAAA
AAECAwQFBgcICQoL / 8QAtRAAAgEDAwIEAwUFBAQAAAF
--xxxxxxxx
解决方案
/ **
*此实用程序函数将文件上传到网址
* * @参数文件路径 - 文件的绝对路径上传
*参数postUrl - 远程地址在哪里发布文件需要
*参数的contentType - 内容类型上传的文件
* @throws异常
* /
公共静态无效postFile(字符串文件路径,字符串postUrl,
字符串pictureTitleStr,字符串pseudoTextStr)
抛出异常{
字符串URL = postUrl;
HttpURLConnection的康恩= NULL;
最后弦乐CRLF =\ r \ N的;
JSONObject的JSON =新的JSONObject();
INT读取动作= 0;
字符串lineEnd =\ r \ N的;
串twoHyphens = - ;
字符串边界=XXXXXXXX;
字符串EndBoundary =;
INT maxBufferSize = 1 * 1024 * 1024;
HTT presponse响应= NULL;
//拥有的HttpClient通过接受的网址以及密钥库/信任证书响应HTTP和HTTPS URL连接
尝试 {
密钥库的trustStore = KeyStore.getInstance(密钥库
.getDefaultType());
trustStore.load(NULL,NULL);
SSLSocketFactory的SF =新MySSLSocketFactory(的trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
的HttpParams PARAMS =新BasicHttpParams();
HttpProtocolParams.setVersion(参数,可以HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(参数,可以HTTP.UTF_8);
HttpProtocolParams.setUserAgent(参数,可以YourAppName / 1.1);
HttpConnectionParams.setStaleCheckingEnabled(参数,可以假);
HttpConnectionParams.setConnectionTimeout(参数,可以20 * 1000);
HttpConnectionParams.setSoTimeout(参数,可以20 * 1000);
HttpConnectionParams.setSocketBufferSize(PARAMS,8192);
HttpClientParams.setRedirecting(参数,可以假);
SchemeRegistry注册表=新SchemeRegistry();
registry.register(新计划(HTTP,PlainSocketFactory
.getSocketFactory(),80));
registry.register(新计划(https开头,SF,443));
ClientConnectionManager CCM =新ThreadSafeClientConnManager(
参数,可以登记);
mHttpClient =新DefaultHttpClient(CCM,则params);
}赶上(例外五){
}
字符串base64En codedCredentials = Base64.en codeToString((用户名+:+密码).getBytes(US-ASCII),
Base64.DEFAULT);
的System.out.println(恩codeD信贷+ base64En codedCredentials);
json.put(伪,pseudoTextStr);
json.put(标题,pictureTitleStr);
串jsonStr = json.toString();
//的System.out.println(JSON值+ jsonStr);
URL URL2 =新的URL(postUrl);
位图BM = BitmapFactory.de codeFILE(文件路径);
ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
bm.com preSS(Bitmap.Com pressFormat.JPEG,25,BAOS); // BM是位图对象
byte []的B = baos.toByteArray();
字符串连接codeDIMAGE = Base64.en codeToString(B,Base64.DEFAULT);
字符串str = twoHyphens +边界+ lineEnd;
字符串str2的=内容处置:表格数据;名称= \jsonFile \;
字符串STR3 =内容类型:应用程序/ JSON;
字符串STR4 =内容处置:表格数据;名称= \imgName \;
STR5的String =内容类型:图像/ JPEG;
字符串str6 = twoHyphens +边界+ twoHyphens;
字符串StrTotal = STR + STR2 +\ r \ N+ STR3 +\ r \ N+\ r \ N+ jsonStr +\ r \ N+ STR
+ STR4 +\ r \ N+ + STR5\ r \ N+\ r \ N+ EN codeDIMAGE +\ r \ N+ str6;
//System.out.print("Multipart请求字符串为+ StrTotal);
HttpPost后=新HttpPost(postUrl);
post.addHeader(BasicScheme.authenticate(新UsernamePasswordCredentials(
用户名,密码),UTF-8,假));
post.addHeader(内容类型,多部分/格式数据;边界=+界);
//的System.out.println(发送邮代理请求:+后);
StringEntity SE =新StringEntity(StrTotal);
se.setContentEncoding(UTF-8);
post.setEntity(SE);
响应= mHttpClient.execute(后);
/ *检查响应* /
。状态code = response.getStatusLine()的getStatus code();
的System.out.println(宀执行完成+状态code);
HttpEntity实体= response.getEntity();
串getResponseText = entity.toString(); // EntityUtils.toString(实体);
的System.out.println(后回应Server文本:
+ getResponseText);
}
I am trying to upload an image to a server along with some JSON data that is collected from a form.
The server has authentication.
METHOD: post
HEADERS:
Authorization Basic d2Vic2VydmljZTpyM05hdTE3Rw==
Content-Type multipart/form-data;boundary=xxxxxxxx
BODY:
--xxxxxxxx
Content-Disposition: form-data; name="jsonFile"
Content-Type: application/json
{"model":"Premium","deviceLongitude":4.79337638,"pseudo":"nickname","deviceLatitude":45.7671507,"year":"2005","email":"email@mail.com","deviceLocale":"fr_FR","title":"my picture"}
--xxxxxxxx
Content-Disposition: form-data; name="imgName"
Content-Type: image/jpeg
//Image data array
/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAAB
AAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAB4KAD
AAQAAAABAAACgAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQH/wAARCAKAAeADAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAA
AAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF
--xxxxxxxx
解决方案
/**
* This utility function will upload the file to the Url
* * @param filePath - absolute path of the file to be uploaded
* @param postUrl - Remote Url where the file need to be posted
* @param contentType - content-type of the uploaded file
* @throws Exception
*/
public static void postFile(String filePath, String postUrl,
String pictureTitleStr, String pseudoTextStr)
throws Exception {
String url = postUrl;
HttpURLConnection conn = null;
final String CrLf = "\r\n";
JSONObject json = new JSONObject();
int bytesRead = 0;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "xxxxxxxx";
String EndBoundary = "";
int maxBufferSize = 1 * 1024 * 1024;
HttpResponse response = null;
// Having HttpClient to respond to both HTTP and HTTPS url connection by accepting the urls along with keystore / trust certificates
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUserAgent(params, "YourAppName/1.1");
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
HttpConnectionParams.setSoTimeout(params, 20 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpClientParams.setRedirecting(params, false);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
mHttpClient = new DefaultHttpClient(ccm, params);
} catch (Exception e) {
}
String base64EncodedCredentials = Base64.encodeToString((userName + ":" + password).getBytes("US-ASCII"),
Base64.DEFAULT);
System.out.println("Encoded Credit " + base64EncodedCredentials);
json.put("pseudo", pseudoTextStr);
json.put("title", pictureTitleStr);
String jsonStr = json.toString();
// System.out.println("JSON VALUE " + jsonStr);
URL url2 = new URL(postUrl);
Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 25, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
String str = twoHyphens + boundary + lineEnd;
String str2 = "Content-Disposition: form-data; name=\"jsonFile\"";
String str3 = "Content-Type: application/json";
String str4 = "Content-Disposition: form-data; name=\"imgName\"";
String str5 = "Content-Type: image/jpeg";
String str6 = twoHyphens + boundary + twoHyphens;
String StrTotal = str + str2 + "\r\n" + str3 + "\r\n" +"\r\n" + jsonStr + "\r\n" + str
+ str4 + "\r\n" + str5 + "\r\n"+"\r\n"+ encodedImage + "\r\n" + str6;
//System.out.print("Multipart request string is "+StrTotal);
HttpPost post = new HttpPost(postUrl);
post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(
userName, password), "UTF-8", false));
post.addHeader("Content-Type","multipart/form-data;boundary="+boundary);
// System.out.println("Sending Post proxy request: " + post);
StringEntity se = new StringEntity(StrTotal);
se.setContentEncoding("UTF-8");
post.setEntity(se);
response = mHttpClient.execute(post);
/* Checking response */
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Http Execute finish " + statusCode);
HttpEntity entity = response.getEntity();
String getResponseText = entity.toString(); // EntityUtils.toString(entity);
System.out.println(" Post Response Text from Server : "
+ getResponseText);
}
上一篇:请问管理的WinRT API包括一种方法来计算一个MD5哈希?方法来、API、WinRT、哈希
下一篇:Genymotion仿真器:安装错误:INSTALL_FAILED_MISSING_SHARED_LIBRARY仿真器、错误、Genymotion、INSTALL_FAILED_MISSING_SHA