Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send file by using http post method in android?

Tags:

android

i am implementing one app related to send file to server.

i am trying to send file to server by using http post method.

i am getting file from sd card by using the fallowing code.

File root = Environment.getExternalStorageDirectory();
String pathToOurFile = root+"111";

My code is looking like as fallows.

StringBuilder response = new StringBuilder();
try {
  HttpPost post = new HttpPost();
  post.setURI(uri);
  List params = new ArrayList();
  params.add(new BasicNameValuePair("paramName", "paramValue"));
  post.setEntity(new UrlEncodedFormEntity(params));
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpResponse httpResponse = httpClient.execute(post);
  if (httpResponse.getStatusLine().getStatusCode() == 200) {
    Log.d(APP_TAG, "HTTP POST succeeded");
    HttpEntity messageEntity = httpResponse.getEntity();
    InputStream is = messageEntity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(
    openFileInput(pathToOurFile)));
    String line;

    while ((line = br.readLine()) != null) {
     Log.v("info",",,,"+line);
     response.append(line);
     }
   } else {
     Log.e(APP_TAG, "HTTP POST status code is not 200");
   }
} catch (Exception e) {
  Log.e(APP_TAG, e.getMessage());
}

but it is not woking properly .

if know the solution please help me

Thanks in advance.

like image 922
kiran Avatar asked May 03 '26 04:05

kiran


1 Answers

This should work, I havent tested the code though.

 import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;

    ...

        public static void uploadFile() throws Exception {
            HttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(uri);
                String pathToOurFile = root+"111";

                File f = new File(pathToOurFile);
                FileBody bin = new FileBody(f);


                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("file", bin);
                reqEntity.addPart("paramName", paramValue);

                httppost.setEntity(reqEntity);

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();

                String postResponse = response.getStatusLine();
        }

    }
like image 58
jithinroy Avatar answered May 04 '26 19:05

jithinroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!