How To Create And Send Multipart Request With Text file In Android - android

I need to fetch data from this site http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
But I am getting this "[ERRO] Problems with your corpus; cannot continue. Please check diagnostics [0 0]" When I am trying to send text file to site.
Here is my code:
String fileUrl = "/sdcard/fish.txt";
File logFileToUpload = new File(fileUrl);
final String BOUNDERY = "------WebKitFormBoundary4Pn8WfAaV8Bv3qqy";
final String CRLF = "\r\n";
// MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBuilder sbBody_1 = new StringBuilder();
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name=\"formtype\"" + CRLF);
sbBody_1.append(CRLF);
sbBody_1.append("simple");
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name =\"corpus\""+"filename=\"fish\"" + CRLF);
//sbBody_1.append("Content-Disposition: form-data; filename=\"fish\"" + CRLF);
String str1="aaa";
sbBody_1.append(CRLF);
//sbBody_1.append(str1);
//sbBody_1.append(CRLF);
//sbBody_1.append(BOUNDERY + "--" );
StringBuilder sbBody_2 = new StringBuilder();
//sbBody_2.append("pratik");
sbBody_2.append(BOUNDERY + "--" );
URL url = new URL("http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// connection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary4Pn8WfAaV8Bv3qqy");
// connection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(sbBody_1.toString().getBytes());
//byte[] bFile = new String(getBytesFromFile(Files1)).getBytes();
// System.out.println(""+bFile);
FileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);
int bytesRead;
byte[] dataBuffer = new byte[1024];
while((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {
out.write(dataBuffer, 0, bytesRead);
System.out.println("output"+dataBuffer +bytesRead);
}
out.write(sbBody_2.toString().getBytes());
//out.write(CRLF.getBytes());
out.flush();
out.close();
BufferedReader bips = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String temp = null;
while ((temp = bips.readLine()) != null) {
System.out.println("output"+temp);
((TextView) findViewById(R.id.textview1))
.setText(temp);
}
bips.close();
connection.disconnect();

It's better to use OkHttp for network requests. You can try this example for multipart request.

Thank you for your help #MaxV i sloved my issue by using OkHttp and POSTMAN

Related

Android HttpURLConnection image uploads but file not recognized as JPEG

I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>

Android code to upload image and json request to a server using multi-part form data

So I have done this earlier multiple times using the MultiPartEntity in apache implementations but now with the deprecation of the APIs I need to use HTTPUrlConnection.
My Server side script looks something like this in php
$userData = urldecode ( $_POST['form'] );
$json = json_decode ( $userData );
$username = $json->emailAddress;
$this->load->model( 'rest_image_upload_model' );
$result = $this->rest_image_upload_model->checkCredentialsAndReturnUserId ($username, $password);
$userId = $result ['mfwid'];
if($userId == 0 || empty($userId) || false == $result){
$responseJson['success'] = false;
$responseJson['message'] = "Username could not be fetched. Contact system admin.";
echo json_decode($responseJson);
return;
}
$firstName = '';
$result = $this->rest_image_upload_model->fetchUsersName( $userId );
$firstName = $result ['first_name'];
if(empty($firstName) || false == $result){
$responseJson['success'] = false;
$responseJson['message'] = "First Name could not be fetched. Contact system admin.";
echo json_decode($responseJson);
return;
}
//end of json part
// Start creating a floder for the image to be uploaded
$foldername = $firstName . '-' . $userId;
if (! is_dir ( 'download/upload/profile/' . $date . '/' . $foldername )){
mkdir ( './download/upload/profile/' . $date . '/' . $foldername, 0777, TRUE );
}
$config ['upload_path'] = './download/upload/profile/' . $date . '/' . $foldername;
$thumbnailRefFilePath = $config['upload_path'];
$config ['allowed_types'] = "jpg|png|JPEG|jpeg|PNG|JPG"; // 'gif|jpg|png|tiff';
$config ['max_size'] = '10240';
$config ['max_width'] = '5000';
$config ['max_height'] = '5000';
$this->load->library ( 'upload', $config );
$this->upload->initialize ( $config );
if (! $this->upload->do_upload ( 'image' )) { // if uploading image failed
$responseJson['success'] = false;
$responseJson['message'] = "File Not Uploaded";
//$upload_data['file_name']='nopic.png';
echo json_encode($responseJson);
return;
} else {
// uploading image success
$upload_data = $this->upload->data(); // save
}
The Android code seems to upload the json part but I get the error. File not uploaded in a json. Below is my android code for this.
public StringBuilder doMultipartPost(String api,
String jsonPost,
String jsonPartKey,
String filePath,
String filePathKey) throws InstyreNetworkException{
String boundary = UUID.randomUUID().toString();
String twoHyphens = "--";
//String attachmentName = "data";
String crlf = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
final String URL = NetworkUtils.BASE_URL + api;
URI uri = new URI(URL);
HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
// FIRST PART; A JSON object
dos.writeBytes(twoHyphens + boundary);
dos.writeBytes(crlf);
dos.writeBytes("Content-Type: application/json");
dos.writeBytes(crlf);
dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
dos.writeBytes(crlf);
dos.writeBytes(crlf);
dos.writeBytes(jsonPost);
dos.writeBytes(crlf);
// SECOND PART; A image..
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
dos.writeBytes(twoHyphens + boundary);
dos.writeBytes(crlf);
dos.writeBytes("Content-Type: jpg");
dos.writeBytes(crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"image\"");
// dos.writeBytes("Content-Disposition: form-data; name=\"attachment_0\";filename=\"" + file.getName() + "\"" + lineEnd);
dos.writeBytes(crlf);
dos.writeBytes(crlf);
dos.writeBytes("Content-Length: " + file.length() + crlf);
dos.writeBytes(crlf);
dos.writeBytes(crlf);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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(crlf);
dos.writeBytes(twoHyphens + boundary + crlf);
fileInputStream.close();
// start reading response
InputStream is = urlConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
is.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I found the part solution here
http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
public StringBuilder doMultipartPost(String api,
String jsonPost,
String jsonPartKey,
String filePath,
String filePathKey) throws NetworkException{
String boundary = UUID.randomUUID().toString();
String twoHyphens = "--";
String crlf = "\r\n";
try {
final String URL = NetworkUtils.BASE_URL + api;
URI uri = new URI(URL);
HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
OutputStream outputStream = urlConnection.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputStream);
// FIRST PART; A JSON object
dos.writeBytes(twoHyphens + boundary);
dos.writeBytes(crlf);
dos.writeBytes("Content-Type: application/json");
dos.writeBytes(crlf);
dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
dos.writeBytes(crlf);
dos.writeBytes(crlf);
dos.writeBytes(jsonPost);
dos.writeBytes(crlf);
File uploadFile = new File(filePath);
String fileName = uploadFile.getName();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"),
true);
writer.append("--" + boundary).append(crlf);
writer.append(
"Content-Disposition: form-data; name=\"" + filePathKey
+ "\"; filename=\"" + fileName + "\"")
.append(crlf);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(crlf);
writer.append("Content-Transfer-Encoding: binary").append(crlf);
writer.append(crlf);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
writer.append(crlf);
writer.append(twoHyphens + boundary + crlf);
outputStream.flush();
inputStream.close();
writer.flush();
// start reading response
InputStream is = urlConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
is.close();
dos.close();
return responseStrBuilder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Send JSON and image with HttpURLConnection in android

i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.php";
try {
// ------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new
// File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
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);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.

Sinch - Message Api not working

Always getting the Bad Request error, error code - 400. Using commons-codec-1.10 jar file but its not available for native Android. here is my code
Date date = new java.util.Date();
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String timestamp = dateFormat.format(date);
String httpVerb = "POST";
String path = "/v1/sms/" + "+918003059919";
String contentType = "application/json";
String canonicalizedHeaders = "x-timestamp:" + timestamp;
String body = "{\"message\":\"" + "Hiiii" + "\"}";
byte[] data = md5Digest(body);
String contentMd5 = Base64.encodeToString(data, 0, data.length,
Base64.DEFAULT);
String stringToSign = httpVerb + "\n" + contentMd5 + "\n"
+ contentType + "\n" + canonicalizedHeaders + "\n"
+ path;
String signature = signature(SinchService.APP_SECRET,
stringToSign);
String authorization = "Application " + SinchService.APP_KEY
+ ":" + signature;
URL url = new URL("https://messagingApi.sinch.com" + path);
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type",
"application/json");
connection.setRequestProperty("x-timestamp", timestamp);
connection.setRequestProperty("authorization", Base64.encodeToString(authorization.getBytes(),Base64.DEFAULT));
OutputStream os = connection.getOutputStream();
os.write(body.getBytes());
StringBuilder response = new StringBuilder();
int status = connection.getResponseCode();
System.out.println("resonse code: "+status);
InputStream iresponse = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
Using android.util.Base64 package to encode but not its not working.
Sinch applications are not automatically whitelisted for sending SMS. Contact them at dev#sinch.com to get your app whitelisted.

Android how to send file and params by HttpURLConnection

I'm developing a app, this one send pictures from sd-card but now I need to send some parameters, how can I do this one?
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes (urlParameters);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
thanks a lot!
you can use MultiPartEntity with the help of it you can upload multiple files as well as parameters. this may help.
You can pass file and paramas in multipartentity like this :
public String reportCrime(String uploadFile, int userid, int crimetype,
String crimedetails, String lat, String longi, String reporteddate) {
String url;
MultipartEntity entity;
try {
url = String.format(Constant.SERVER_URL
+ "push_notification/reportCrime.php");
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//
File file = new File(uploadFile);
if (!file.equals("Image not Provided.")) {
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", uploadFile);
entity.addPart("image", foto);
}
} else {
FormBodyPart image = new FormBodyPart("image", new StringBody(
""));
entity.addPart(image);
}
FormBodyPart userId = new FormBodyPart("userId", new StringBody(
String.valueOf(userid)));
entity.addPart(userId);
FormBodyPart crimeType = new FormBodyPart("crimetype",
new StringBody(String.valueOf(crimetype)));
entity.addPart(crimeType);
FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
new StringBody(crimedetails));
entity.addPart(crimeDetails);
FormBodyPart latittude = new FormBodyPart("latittude",
new StringBody(lat));
entity.addPart(latittude);
FormBodyPart longitude = new FormBodyPart("longitude",
new StringBody(longi));
entity.addPart(longitude);
FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
new StringBody(reporteddate));
entity.addPart(reportedDate);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return "error";
}
HttpParams httpParams = new BasicHttpParams();
HttpContext httpContext = new BasicHttpContext();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Categories

Resources