I am using MultipartEntity upload image with data, but I am unable to post. I have to post some details along with image. I don't know where is the problem, and also debug my code when hitting the post it not working. I don't know how to solve this problem.
File file1 = new File(selectedPath1);
String urlString = "url";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile", bin1);
reqEntity.addPart("Firstname", new StringBody("Firstname"));
reqEntity.addPart("Mobilenumber", new StringBody("Mobilenumber"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
After a long time research, i was able to post image with data to the server.I am follow the below link and modify as my requirement.I think this is helpful to anyone.It is very useful to capture a picture and also i am able to post image with data by using this link
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
try {
CustomMultiPartEntity entity=new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("FirstName", new StringBody(Person.getFirstName()));
entity.addPart("LastName", new StringBody(Person.getLastName()));
entity.addPart("Email", new StringBody(Person.getEmail()));
entity.addPart("Password", new StringBody(Person.getPassword()));
entity.addPart("Mobilenumber", new StringBody(Person.getMobilenumber()));
entity.addPart("uploadedfile", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
responseString = EntityUtils.toString(r_entity);
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
Related
I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"
hello i need when i click to button "send" i send all selected picture ( i have all this picture in table picture[]
in PHP i do this
<input id="uploadImageAct" type="file" name="uploadImageAct[]" data-max-size="2048" accept="image/x-png, image/gif, image/jpeg" style="visibility: hidden" multiple="multiple">
and in android for just one picture i do this but i don't know how i do for multi picture (I put all my picture in table picture[] )
this solution is for one image for FileBody and me i need multi image in one FileBody
public JSONObject post(String url, ArrayList<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("uploadFile")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
Charset chars = Charset.forName("UTF-8");
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue(),chars));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException 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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
How can I change this function so that I can do this
thanks :)
You can upload multiple files in one request along with other string parameters in Android.
For that, you have to include 2 libraries into your project build path, apache-mime4j-0.6.jar and httpmime-4.0.1.jar.
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "Your server location";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Or simply visit CoderzHeaven, it may help you.
I have created the following function for getting json from server as below :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException 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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
when user in bad connection, it just loading without give any notification, my question is : how can i add such as toast when request time out or bad connection?
I know, its been A long time, but I try to help, lets try to add this one :
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
and in your code, this will be :
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch(ConnectTimeoutException e){
Log.e("Timeout Exception: ", e.toString());
} catch(SocketTimeoutException ste){
Log.e("Timeout Exception: ", ste.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and to show message request time out, you can add such as alert message on your onPostExecute() if the result null or empty.
First of all set HttpRequestTimeOut like given below then add this logic into try and catch and add toast message into catch block when request timeout fails it'll show you toast message.
url = new URI(s.replace(" ", "%20"));
Log.e("my webservice", "My webservice : " + url);
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = null;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
// Execute HTTP Post Request
httpResponse = httpClient.execute(httpget);
I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, 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);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
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;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}
My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;