I want to send an image captured by camera to a server, which creates blob key. I am not getting how to send that image to the server. In which format is the image is sent?
I am trying to send parameters through HttpParams.
This is my code but the data is not going to server. What is the problem?
String name=tname.getText().toString();
String addr=taddr.getText().toString();
String age=tage.getText().toString();
String cnct=tcnct.getText().toString();
String gen=tgen.getText().toString();
String wtm=twtm.getText().toString();
ba1=Base64.encodeToString(imageform, 0);
Date d=new Date();
String date=d.toString();
InputStream i1;
String back="";
HttpParams p=new BasicHttpParams();
p.setParameter("vname",name);
p.setParameter("address", addr);
p.setParameter("age", age);
p.setParameter("contact", cnct);
p.setParameter("gender", gen);
p.setParameter("whomto", wtm);
p.setParameter("myFile", ba1);
try {
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost res=new HttpPost(result);
HttpResponse response = httpclient.execute(res);
HttpEntity entity = response.getEntity();
i1 = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(i1,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
if ( reader.readLine() == null) {
Log.e("inside if","No data");
} else {
String line = reader.readLine();
i1.close();
back=sb.toString();
}
I am not getting any errors or exceptions.
You should make an MultipartPost and add the file to your MultipartEntity as follows :
multipartEntity.addPart("data", new FileBody(capturedImagePath));
You should have a look a this answer Multipart post with Android for a more detailed answer.
Encode the image, using Base64, to a String and send it using MultipartEntity.
In php retrieve the string an unpack it with base64_decode to the image.
Check this question:
https://stackoverflow.com/questions/10145417/android-send-image-through-http-post
Related
I have one api. In that i have to pass some parameters, some parameters among them i have to pass them like array arraylist. My example Request ?Url is as below:
http://yehki.epagestore.in/app_api/order.php?customer_id=3&address_id=31&products%5B0%5D%5BproductName%5D=rt&products%5B0%5D%5Bproduct_id%5D=41&products%5B0%5D%5Bquantity%5D=2&products%5B0%5D%5Bunit%5D=1&products%5B0%5D%5BunitPrice%5D=400
MY API request with parameters
I havej no idea how to build; this kind if request url... Can anyone suggest me for it what should i do..Or any help code?
private String httpGetRequest() throws Exception
{
String receiveStr = "";
String urlRequest = urlString;
DefaultHttpClient client = null;
HttpResponse execute;
client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urlRequest);
execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = buffer.readLine()) != null)
stringBuffer.append(line);
client.getConnectionManager().shutdown();
client = null;
receiveStr = stringBuffer.toString();
return receiveStr;
}
Then for parse JSON you can use usefull GSON library.
You must create variable urlString in code :
String urlString = "http://yehki.epagestore.in/app_api/order.php?customer_id=3&address_id=31&products%5B0%5D%5BproductName%5D=rt&products%5B0%5D%5Bproduct_id%5D=41&products%5B0%5D%5Bquantity%5D=2&products%5B0%5D%5Bunit%5D=1&products%5B0%5D%5BunitPrice%5D=400"
by your current Get Http parametrs: customer_id, address_id, etc
This code above return to you String variable like this: "{"status":"Sucess","order_id":1070,"order_product_id":[1325],"complete_order_time":["1"],"product_id":["41"],"payee_key":["2511131I093517"]}"
Then you must parse it JSON string variable. Very usefull library for parse JSON string is GSON library . Read this https://sites.google.com/site/gson/gson-user-guide
I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app. My upload code is like below:
public String uploadFile() throws Exception
{
String result = "";
try
{
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(_url);
request.setHeader("Accept", "application/json");
File file=new File(filePath);
String fileName=file.getName();
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
imageEntity.addPart("imageName", new StringBody(fileName));
imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
request.setEntity(imageEntity);
response = httpClient.execute(request);
InputStream dataStream = response.getEntity().getContent();
BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
String line = "";
while ((line = dataReader.readLine()) != null)
result+=line;
}
catch (Exception e)
{
}
return result;
}
I get response from my server but in my web service code Request.Files has no file. If I change the line:
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
to
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
app is in process for a long time (about 3-4 minutes) and throws error. This is caused if I add an image. If I send only StringBody without FileBody, I get response from server and Request.Files in my webservice code return file count correctly. How can I fix this problem and upload image correctly? Any suggestion?
I'm sending images and json text from the android client to a tomcat server and the other way around by using Multipart HttpPost's. Sending a Multipart Entity to the server is no big deal, because you can process the parts easily using request.getPart(<name>). But at the client side you can only access the response as a Stream. So I end up appending both, the JSON string and the image to the same ServletOutputStream and have to parse them by hand on the client side. I found apache-mime4j in the web but its hardly documented and I cant find a single example how to use it.
On the server side I build the response like this:
ServletResponse httpResponse = ctx.getResponse();
ResponseFacade rf = (ResponseFacade) httpResponse;
rf.addHeader("Access-Control-Allow-Origin", "*");
rf.addHeader("Access-Control-Allow-Methods", "POST");
rf.addHeader("content-type", "multipart/form-data");
httpResponse.setCharacterEncoding("UTF-8");
MultipartResponse multi = new MultipartResponse((HttpServletResponse) httpResponse);
ServletOutputStream out = httpResponse.getOutputStream();
multi.startResponse("text/plain");
out.println(CMD + "#" + content);
multi.endResponse();
multi.startResponse("image/jpeg");
out.write(data);
multi.endResponse();
multi.finish();
ctx.complete();
And on the client side on Android I want to access the text and the image data:
InputStream is = response.getEntity().getContent();
MimeStreamParser parser = new MimeStreamParser();
MultipartContentHandler con = new MultipartContentHandler();
parser.setContentHandler(con);
try {
parser.parse(is);
String json = con.getJSON(); //get extracted json string
byte[] imgBytes = con.getBytes(); //get extracted bytes
} catch (MimeException e) {
e.printStackTrace();
} finally {
is.close();
}
class MultipartContentHandler implements ContentHandler{
public void body(BodyDescriptor bd, InputStream in) throws MimeException, IOException {
//if MIME-Type is "text/plain"
// process json-part
//else
// process image-part
}
In the method body(BodyDescriptor bd, InputStream in) my whole response is treated as text\plain mime type. So I finally have to parse every byte manually again and the whole apache-mime4j is useless. Can you tell me what I am doing wrong? Thanks!
Ok i finally solved it myself. No here's what i did:
First I need to create a multipart/mixed Response at the server side. It can be done using apache-mime-4j API:
ServletResponse httpResponse = ctx.getResponse();
ResponseFacade rf = (ResponseFacade) httpResponse;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("multipart/mixed");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "SEPERATOR_STRING",Charset.forName("UTF-8"));
entity.addPart("json", new StringBody(CMD + "#" + content, "text/plain", Charset.forName("UTF-8")));
entity.addPart("image", new ByteArrayBody(data, "image/jpeg", "file"));
httpResponse.setContentLength((int) entity.getContentLength());
entity.writeTo(httpResponse.getOutputStream());
ctx.complete();
Now at the client side to access the MIME-Parts of the HttpResponse I use the javax.mail API.
ByteArrayDataSource ds = new ByteArrayDataSource(response.getEntity().getContent(), "multipart/mixed");
MimeMultipart multipart = new MimeMultipart(ds);
BodyPart jsonPart = multipart.getBodyPart(0);
BodyPart imagePart = multipart.getBodyPart(1);
But you can't use the native API, instead take this one http://code.google.com/p/javamail-android/
Now you can proceed handling your individual parts.
It is also possible with apache-mime-4j:
HttpURLConnection conn = ...;
final InputStream is = conn.getInputStream();
try {
final StringBuilder sb = new StringBuilder();
sb.append("MIME-Version: ").append(conn.getHeaderField("MIME-Version")).append("\r\n");
sb.append("Content-Type: ").append(conn.getHeaderField("Content-Type")).append("\r\n");
sb.append("\r\n");
parser.parse(new SequenceInputStream(new ByteArrayInputStream(sb.toString().getBytes("US-ASCII")), is));
} catch (final MimeException e) {
e.printStackTrace();
} finally {
is.close();
}
HttpClient httpclient1 = new DefaultHttpClient();
HttpParams p=new BasicHttpParams();
p.setParameter("vname",name);
p.setParameter("address", addr);
p.setParameter("age", age);
p.setParameter("contact", cnct);
p.setParameter("gender", gen);
p.setParameter("whomto", wtm);
p.setParameter("myFile", f);
HttpPost res1=new HttpPost(result);
res1.setHeader("Content-Type", "text/plain");
res1.setHeader("Content-Type","image/jpeg");
HttpResponse response1 = httpclient1.execute(res1);
HttpEntity entity1 = response1.getEntity();
i1 = entity1.getContent();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(i1,"iso-8859-1"),8);
StringBuilder sb1 = new StringBuilder();
String line1 = null;
if((line1 = reader1.readLine()) != null) {
sb1.append(line1);
back=sb1.toString();
}
else{
Log.e("GET data","null");
}
i1.close();
Log.e("GET",""+back);
//Server Code
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("myFile");
final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(new BlobKey(blobKey.getKeyString()));
System.out.println(blobInfo.getContentType());
if(!blobInfo.getContentType().equalsIgnoreCase("image/jpeg")){
blobstoreService.delete(blobInfo.getBlobKey());
res.getWriter().println("Please Provide JPG image only");
}
I am sending one image file with some other data to server.I am not getting any error or exception But when I am printing the "back",in log it is showing "The request's content type is not accepted on this URL". "f" is my image file..What is the problem?
Have a look at my answer to a similar question as yours: link
It will save you the hassle of writing server side code and letting you android app send data eg. images to it.
You are setting the Content-Type header to two different values, neither of which is "multipart/form-data" which I believe is what you need when sending an file.
Here is an answer that should help:
https://stackoverflow.com/a/3003402/412558
I am uploading a large string to web-service. The string contains new line character which is written as "\n".
The data looks some thing like:
05/06/2012 11:35:43 AM- DB exists, transferring data\n05/06/2012
11:48:20 AM- loadUserSpinners, cursor.getCount()=2\n05/06/2012
11:48:20 AM- Battery: 50%\n05/06/2012 11:48:20 AM- ITEM SELECTED: 0
the above data is stored in string JsonArrObj. To upload the data/string, i am using the following code:
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 360000; //6 minutes
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 420000; //7 minutes
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
JSONArray jsonParams = new JSONArray();
Object[] params={IPAddress,Database,DbName,DbPassword,JsonArrObj};
for (int i = 0; i < params.length; i++) {
jsonParams.put(params[i]);
}
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("id", Id);
jsonRequest.put("method", FunctionName);
jsonRequest.put("params", jsonParams);
JSONEntity entity = new JSONEntity(jsonRequest);
entity.setContentType("application/json; charset=utf-8");
HttpPost request = new HttpPost(URL);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
InputStream content = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content,"iso-8859-1"),8);
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
LogE("result line: "+line);
String str=convertString(line);
parseJson(str);
}
content.close();
}
The string is uploaded successfully. The problem I am facing is: while string is being converted to jsonParams, the "\n" in the string data gets converted to "\\n" as a result, on the server side, it shows a small box in stead of new line.
When I open this string in NOTEPAD application, it displays small boxes. But when I open it in WORDPAD app, text is displayed on a new line. According to me, I might have entered in-correct "content-type" or encoding. Please suggest a solution for the same.
JsonArrObj= URLEncoder.encode(JsonArrObj, "utf-8"); gave error while uploading itself...
The data which is sent in the jsonParams- jsonArrObj finally looks like:
05\/06\/2012 04:05:52 PM- DB exists, transferring
data\\n05\/06\/2012 04:32:56 PM- loadUserSpinners,
cursor.getCount()\\u003d2\\n05\/06\/2012 04:32:56 PM- Battery:
50%\\n05\/06\/2012 04:32:56 PM- ITEM SELECTED: 0
Well, the encoder escapes your newline characters. If you want to transport newline chars properly, you can encode the whole stream with base64. If your target os (for data to send) is Windows then you should use \r\n, if mac then \r if unix\linux then \n. After encoding data try to send the encoded and decode it on the other side. For base64 Mr. Google will convince you.
Hey why don't you use the Unicode values for \n as and any other character that is creating this problem
like this U+002FU+006E