Upload file using HTTP Post multipart - 4Sharing API J2ME - java

I'm currently developing a J2ME app. I'm having problems with file uploading. I dont seem to know what part of my code is wrong. Here is my code:
public void UploadImage(long newFileId, String url, String bytes){
HttpConnection conn = null;
OutputStream os = null;
InputStream s = null;
StringBuffer responseString = new StringBuffer();
try
{
System.out.println(System.getProperty("HTTPClient.dontChunkRequests"));
conn.setRequestMethod(HttpConnection.POST);
conn = (HttpConnection)Connector.open(url);
conn.setRequestProperty("resumableFileId", ""+newFileId);
conn.setRequestProperty("resumableFirstByte", ""+0);
conn.setRequestProperty("FilePart", bytes);
// Read
s = conn.openInputStream();
int ch, i = 0, maxSize = 16384;
while(((ch = s.read())!= -1 ) & (i++ < maxSize))
{
responseString.append((char) ch);
}
conn.close();
System.out.println(responseString.toString());
String res = uploadFinishFile(newFileId, bytes);
if(res.length()>0)
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
This is the java code that im trying to convert to j2me:
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity me = new MultipartEntity();
StringBody rfid = new StringBody("" + newFileId);
StringBody rfb = new StringBody("" + 0);
InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart");
me.addPart("resumableFileId", rfid);
me.addPart("resumableFirstByte", rfb);
me.addPart("FilePart", isb);
post.setEntity(me);
HttpResponse resp = client.execute(post);
HttpEntity resEnt = resp.getEntity();
String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f)));
if(res.isEmpty())
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
} catch (Exception ex) {
System.out.println("Upload failed: "+ex.getMessage());
}

You are uploading the file passing the parameters as HTTP headers, instead of sending the image in the HTTP message body using multipart file upload, compatible with the code you're converting.
Take a look at HTTP Post multipart file upload in Java ME. You can use the HttpMultipartRequest class and change your code to:
Hashtable params = new Hashtable();
params.put("resumableFileId", "" + newFileId);
params.put("resumableFirstByte", "" + 0);
HttpMultipartRequest req = new HttpMultipartRequest(
url,
params,
"FilePart", "original_filename.png", "image/png", isb.getBytes()
);
byte[] response = req.send();

Related

Upload image to Spring Server API in Android

i'm traying to upload a image in Android App to my api, but i have this menssage:
"The current request is not a multipart request"
I've this code in my app android:
#Override
protected String doInBackground(String... uri) {
// url where the data will be posted
String postReceiverUrl = "http://...";
Log.v("TEST", "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
try {
// the URL where the file will be posted
File file = new File(mCurrentPhotoPath);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("TEST ", "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
And in my API i've this code:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public
#ResponseBody
String handleFileUpload(#RequestParam(value = "file", required = false) MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File file1 = new File("test.jpg");
FileOutputStream fos = new FileOutputStream(file1);
BufferedOutputStream stream =
new BufferedOutputStream(fos);
stream.write(bytes);
stream.close();
System.out.println("The path is: ");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
return "You successfully uploaded \"test.jpg\"!";
} catch (Exception e) {
return "You failed to upload test.jpg => " + e.getMessage();
}
} else {
return "You failed to upload test.jpg because the file was empty.";
}
}
How can i do this?
May be the following code help to you to upload the image in server
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(<server api url>);
MultipartEntity entity = new MultipartEntity();
File myFile = new File(<file_path>);
FileBody fileBody = new FileBody(myFile);
entity.addPart("upload_param_name",fileBody);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
Log.d("SOAP ", "Result : " + xmlString.toString());
Also for this, you have to use the .jar of apache-mine and httpmine in your apps libs folder.
Finally i convert the image in base64 and send to server how a String and in my Server reconvert to image.
Thanks!

Sending POST data to website and getting answer

I have a problem with getting direct link to video. I want to play it in my WebView/VideoView. How to send POST request and recieve answer with direct link from website which decode such things:
videotools.12pings.net
Is there any way to do that?
Example: put link in the website form - than click a button - direct link is ready under the button
final HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
HttpConnectionParams.setConnectionTimeout(httpParameters, 7000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response = client.execute(new HttpGet(path));
HttpEntity entity = response.getEntity();
InputStream imageContentInputStream = entity.getContent();
path is the variable that contains your URL
I hope this will help you..
*You need to get
httpcomponents-client-4.1.zip and apache-mime4j-0.6.1-bin.zip
Add
apache-mime4j-0.6.1-bin.zip
and
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
from the lib folder in httpcomponents-client-4.1.zip
- See more at: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/#sthash.N7qT8apH.dpuf*
try {
MultipartEntity multipart = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
FormBodyPart office = new FormBodyPart("office",
new StringBody(getOffice));
multipart.addPart(office);
String imageCount = Integer.toString(drawableList.size());
System.out.println("ImageCount : " + imageCount);
FormBodyPart imgNo = new FormBodyPart("imgNo", new StringBody(
imageCount));
multipart.addPart(imgNo);
} catch (Exception e) {
// TODO: handle exception
}
try {
System.out.println("result : " + multipart.getContentLength());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CommunicatorUrl.ADD_INCIDENT);
httppost.setEntity(multipart);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
} catch (Exception e) {
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
basically this MultipartEntity is useful for sending multiple images and datas to server using post method
String paramUsername = "username";
String paramPassword = "password";
System.out.println("*** doInBackground ** paramUsername " + paramUsername + "
paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.xxxxxxxxxxxxxx.php");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("ParamUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}

Access URL with Java

I am writing an Android program that needs to access a URL with GET variables which will be logged into a database. All I need to do is open a URL so the web server will log the data! How should I go about this?
Thanks
// default HTTP Client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use this.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URL HERE"));
startActivity(browserIntent);
Hope this helps.
EDIT:
Ok, use this. It calls the URL without opening a browser
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("URL HERE");
HttpResponse response = httpClient.execute(httpGet, localContext);
You can also use HttpUrlConnection. Sample code -
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
And obviously since it is a netowork call you cannot do it in main/UI thread. So you can do it in async task. More details and Source

Http MultiPart request

I am trying to upload an image (multi-part/form-data) using httpClient library. I am able to upload the image using httpPost Method and a byteArrayRequestEntity. Following is the code I used:
File file = new File(imageFilePath);
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("https://domain/link/folderId/files?access_token="+accessToken);
method.addRequestHeader("Content-Type","multipart/form-data;boundary=AaB03x");
String boundary = "AaB03x";
StringBuilder builder = new StringBuilder();
builder.append("--");
builder.append(boundary+"\r\n");
builder.append("Content-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"");
builder.append("\r\n");
builder.append("Content-Type: image/jpeg");
builder.append("\r\n");
builder.append("\r\n");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(builder.toString().getBytes("utf-8"));
builder.setLength(0);
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[4096];
int nbRead = is.read(buffer);
while(nbRead > 0) {
baos.write(buffer, 0, nbRead);
nbRead = is.read(buffer);
}
is.close();
builder.append("\r\n");
builder.append("--");
builder.append(boundary);
builder.append("--");
builder.append("\r\n");
baos.write(builder.toString().getBytes("utf-8"));
method.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray(), "multipart/form-data; boundary=\"" + boundary + "\""));
System.out.println(method.getRequestEntity().toString());
client.executeMethod(method);
But the project i am working on requires me to use an httpRequest and not Http PostMethod.
I tried with basicHttpEntityEnclosingRequest, but the setEntity method for the same accepts only a httpEntity (i was using ByteArrayRequestEntity).
Could anyone help me with how to modify the code so that it uses a HttpRequest (or its subtype) instead of a PostMethod?
- I have used apache-mime library for posting the image with message to the Webserver.
Here is the code from my production environment:
public String postDataCreation(final String url, final String xmlQuery,final String path){
final StringBuilder sa = new StringBuilder();
final File file1 = new File(path);
Thread t2 = new Thread(new Runnable(){
public void run() {
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("dish_photo", bin1);
reqEntity.addPart("xml", new StringBody(xmlQuery));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sa.append(s);
}
Log.d("Check Now",sa+"");
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
});
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sa.toString());
return sa.toString();
}

Trying to send sqlite database from android phone to web server

I'm trying to send a sqlite database from my android phone to a web server. I get no errors when the code executes, however the database doesn't appear on the server. Here is my php code and code to upload the file from the android phone. The connection response message is get is "OK" and the response from the http client I get is org.apache.http.message.BasicHttpResponse#4132dd40.
public void uploadDatabase() {
String urli = "http://uploadsite.com";
String path = sql3.getPath();
File file = new File(path);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urli);
URL url = new URL(urli);
connection = (HttpURLConnection) url.openConnection();
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
HttpResponse response = httpclient.execute(httppost);
String response2 = connection.getResponseMessage();
Log.i("response", response.toString());
Log.i("response", response2.toString());
} catch (Exception e) {
}
}
<?php
$uploaddir = '/var/www/mvideos/uploads/';
$file = basename($_FILES['userfile']['name']);
$timestamp = time();
$uploadfile = $uploaddir . $timestamp . '.sq3';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "OK";
} else {
echo "ERROR: $timestamp";
}
?>
I based my code on this example and it worked fine.
String pathToOurFile = "/data/dada.jpg";
String urlServer = "http://sampleserver.com";
try {
FileInputStream fis = new FileInputStream(new File(pathToOurFile));
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(urlServer);
byte[] data = IOUtils.toByteArray(fis);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),pathToOurFile);
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");
MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody bin = new FileBody(new File(pathToOurFile));
multipartContent.addPart("uploadedfile", bin);
multipartContent.addPart("name", sb1);
multipartContent.addPart("status", sb2);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
} catch (Throwable e) {
e.printStackTrace();
}

Categories