POST Request with android - java

I'm new to android development. I have this code to make a POST Request to a server with PHP.
HttpURLConnection conn;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = Long.toHexString(System.currentTimeMillis());
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e(MainActivity.TAG, "Source File not exist :" + imagepath);
uploadButton.setEnabled(true);
return 0;
} else {
try {
postName = "Filedata[]";
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// 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");
String cookie = CookieManager.getInstance().getCookie(upLoadServerUri);
conn.setRequestProperty("Cookie", cookie);
conn.setRequestProperty("User-Agent", MainActivity.userAgent);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty(postName, sourceFileUri);
String charset = "UTF-8";
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
// Send normal param.
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"to\"").append(lineEnd);
writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
writer.append(lineEnd).append(id).append(lineEnd).flush();
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"content\"").append(lineEnd);
writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
writer.append(lineEnd).append("image").append(lineEnd).flush();
// Send the picture
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"" + postName + "\"; filename=\"" + sourceFileUri + "\"").append(lineEnd);
writer.append("Content-Type: ").append(HttpURLConnection.guessContentTypeFromName(sourceFileUri)).append(lineEnd);
writer.append("Content-Transfer-Encoding: binary").append(lineEnd);
writer.append(lineEnd).flush();
copyFile(fileInputStream, output);
output.flush();
writer.append(lineEnd).flush();
// End of multipart/form-data.
writer.append(twoHyphens).append(boundary).append(twoHyphens).append(lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
// final String serverResponseMessage = conn.getResponseMessage();
InputStream stream = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
// put output stream into a string
BufferedReader br = new BufferedReader(isReader);
String serverResponsePre = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
serverResponsePre += line;
}
final String serverResponse = serverResponsePre;
if (serverResponseCode == 200) {
Toast.makeText(Uploader.this, "File Upload Complete:" + serverResponse, Toast.LENGTH_LONG).show();
}
fileInputStream.close();
this.finish();
}catch(MalformedURLException ex){
dialog.dismiss();
ex.printStackTrace();
Log.e(MainActivity.TAG, "error: " + ex.getMessage(), ex);
uploadButton.setEnabled(true);
}catch(Exception e){
dialog.dismiss();
e.printStackTrace();
Toast.makeText(Uploader.this, "Got Exception : see logcat ", Toast.LENGTH_LONG).show();
Log.e(MainActivity.TAG, "Exception : " + e.getMessage(), e);
uploadButton.setEnabled(true);
}
dialog.dismiss();
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
On the android side, no error is thrown. On the PHP Side, $_FILES["Filedata"] is set, but the size of the file is 0 and no tmp_name is set. Am I missing something? I can't spot the error. Thank you in advance.

Related

Problems using HttpUrlconnection to do login and upload an image

I've made an API which has an authorization part and a body part. The body part is for users to upload an image. For the basic auth part, it just need the username and the password. For the uploading part, it needs two parameters and an jpeg image file. I just got from some resources for uploading file but not combining the login part, so I modify it myself, but I don't know what's wrong in my code, it doesn't work. The following is my code:
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpsURLConnection) url.openConnection();
///// certification
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
connection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
String a = username + ":" + password;
byte[] data = a.getBytes();
String info = "Basic " + Base64.encodeToString(data, Base64.DEFAULT);
connection.setRequestProperty("Authorization", info);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
throw new CustomException("error e");
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I don't know why it doesn't work.
Does anyone know how to use httpurlconnection to do both login and uploading files? In my code, I add both the following lines, is this a problem? I mean use "Content-Type" for multiple times(Login and Uploading files):
For Login part:
connection.setRequestProperty("Content-Type", "text/plain");
For uploading file part:
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
But I call them at the same time(same function), is this a problem?

How to upload file with other string data using HttpURLConnection in android?

I want to upload file with other string data to the server in one request using HttpURLConnection (not using MultiPartEntityBuilder)...Currently I can send the file but not the other string data with it !! Here is my current code for sending the file to server :
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = null;
String fileName = sourceFile.getName();
try {
connection = (HttpURLConnection) new URL(FILE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("token", sharedpreferences.getString("token", ""));
connection.setRequestProperty("app_version", app_version);
connection.setRequestProperty("api_version", api_version);
connection.setDoOutput(true);
String metadataPart = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ ""
+ "\r\n";
String fileHeader1 = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"myFile\"; filename=\""
+ fileName
+ "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = sourceFile.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", "" + requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead; // Here progress is total uploaded bytes
publishProgress((int) ((progress * 100) / sourceFile.length())); // sending progress percent to publishProgress
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
// Exception
} finally {
if (connection != null) connection.disconnect();
}
return null;
Any help would be appreciated !!Thank you...

how to send multipart data in the form of form data in android using httpurlconnection

This is the way i have to send
I have tried with many answers but is not able to undersatnd the data value and the method used . i m new to multipart . Kindly help
This is the code it returns satus ok but returns response code as null
String charset = "UTF-8";
File uploadFile1 = new File("/storage/emulated/0/DCIM/Camera/IMG_20161127_101131.jpg");
String requestURL = "http://10.238.48.30:8081/socialapi/social/addimage/v1/51";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
String fileName = uploadFile1.getName();
writer.append(
"Content-Disposition: form-data; name=\"" + "uploadimage"
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
/*writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);*/
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
//writer.append(LINE_FEED);
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);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
writer.flush();
// writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;

Android: Why am I unable to upload an image to a web server?

I'm using HttpUrlConnection to upload an image to a web server. When I run the app and attempt to upload an image I get a Http response 200 as well as receive the filename and the imageid of the supposed image that has been uploaded, but when i check the server the image was not uploaded. The filename and the id are now part of the list but when I attempt to retrieve the image it returns null.
public String uploadFile(String apiPath, String filePath, String type)
{
String path = "";
String result = "";
switch (type)
{
case "M":
path = "Merchant/" + apiPath;
break;
case "C":
path = "Customer/" + apiPath;
break;
}
Log.i(ApiSecurityManager.class.getSimpleName(), m_token);
String href = "http://tysomapi.fr3dom.net/" + path + "?token=" + m_token;
Log.i(ApiSecurityManager.class.getSimpleName(), href);
try
{
String myIp = getIp();
URL url = new URL(href);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "java");
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary = " + boundary);
conn.setRequestProperty("X-Forwarded-For", myIp);
conn.setDoOutput(true);
File file = new File(filePath);
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
ds.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"" + LINE_FEED);
ds.writeBytes("ContentType: image/peg" + LINE_FEED);
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
FileInputStream fStream = new FileInputStream(file);
int bytesAvailable = fStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
ds.write(buffer, 0, bufferSize);
bytesAvailable = fStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fStream.read(buffer, 0, bufferSize);
}
ds.writeBytes(LINE_FEED);
ds.writeBytes(twoHyphens + boundary + twoHyphens + LINE_FEED);
fStream.close();
ds.flush();
ds.close();
Log.i(getClass().getSimpleName(), "Response Code: " + conn.getResponseCode());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null)
{
result = result + output;
}
conn.disconnect();
}
catch (
MalformedURLException e
)
{
e.printStackTrace();
}
catch (
IOException e
)
{
e.printStackTrace();
}
return result;
}
I was able to fix the problem by using PrintWriter and OutputStream instead of DataOutputStream to pass the headers and the image.

Android - HTTPURLConnection fails while posting multiple inputs

I am trying to post 5 string values and an image to php server by using HTTPURLConnection. Getting Response code as 200 and Response message as OK but actual response after posting is not getting. Below is the code i am using:
public int sendRprtWithImageToServer(String getImagePath, String strEmailList){
String upLoadServerUri = "My URL";
String fileName = getImagePath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int serverResponseCode = 0;
File sourceFile = new File(getImagePath);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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("stringkey1", stringvalue1);
conn.setRequestProperty("stringkey2", stringvalue2);
conn.setRequestProperty("stringkey3", stringvalue3);
conn.setRequestProperty("stringkey4", stringvalue4);
conn.setRequestProperty("stringkey5", stringvalue5);
conn.setRequestProperty("stringkey6", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey1\";filename=\""+ stringvalue1 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey2\";filename=\""+ stringvalue2 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey3\";filename=\""+ stringvalue3 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey4\";filename=\""+ stringvalue4 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey5\";filename=\""+ stringvalue5 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey6\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
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);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
InputStream is = conn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
Log.d("String response ", sb.toString());
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
}
Can anyone help me how to pass multiple parameters for HTTPURLConnection
I think you should use filebody to get file attach itself inside and 5 other string should be embedded inside multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, List<String> taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
System.out.println("file name" + filelist.get(i));
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
}
for (int i = 0; i < taglist.size(); i++) {
reqEntity.addPart("dtype" + i, new StringBody(taglist.get(i)));
}
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}

Categories

Resources