Data Send Utils : Http Connection « Network « Android






Data Send Utils

     
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.util.Base64;
import android.util.Log;

/**
 * Send Data Utils
 * 
 * @author wpc
 * 
 */
public class DataSendUtils {

  public static boolean httpPost(String pathToOurFile, String urlServer,
      String formName) {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    boolean sendSuccess = true;

    try {
      FileInputStream fileInputStream = new FileInputStream(new File(
          pathToOurFile));

      URL url = new URL(urlServer);
      connection = (HttpURLConnection) url.openConnection();

      // Allow Inputs & Outputs
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setUseCaches(false);

      // Enable POST method
      connection.setRequestMethod("POST");

      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);

      outputStream = new DataOutputStream(connection.getOutputStream());
      outputStream.writeBytes(twoHyphens + boundary + lineEnd);
      outputStream.flush();
      outputStream.writeBytes("Content-Disposition: form-data; name=\""
          + formName + "\";filename=\"" + pathToOurFile + "\""
          + lineEnd);
      outputStream.flush();
      outputStream.writeBytes(lineEnd);
      outputStream.flush();

      bytesAvailable = fileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // Read file
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        outputStream.flush();
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      outputStream.writeBytes(lineEnd);
      outputStream.flush();
      outputStream.writeBytes(twoHyphens + boundary + twoHyphens
          + lineEnd);
      outputStream.flush();
      fileInputStream.close();
      outputStream.close();

      connection.getResponseCode();
      connection.getResponseMessage();

    } catch (Exception ex) {
      sendSuccess = false;
    } finally {
      connection.disconnect();
    }
    return sendSuccess;
  }

  /**
   * TODO FIX Check the file length, it's long not int.This may lead the
   * problem.
   * 
   * @param fileName
   * @param url
   * @return
   */
  public static boolean httpPostBase64(String fileName, String url,
      String formKey, String inputName) {
    try {
      File file = new File(fileName);
      FileInputStream in = new FileInputStream(file);
      byte[] buffer = new byte[(int) file.length() + 100];
      int length = in.read(buffer);
      String data = Base64.encodeToString(buffer, 0, length,Base64.DEFAULT);

      HttpPost httpRequest = new HttpPost(url);
      List<NameValuePair> params = new LinkedList<NameValuePair>();
      params.add(new BasicNameValuePair("hl", "en_GB"));
      params.add(new BasicNameValuePair("formkey", formKey));
      params.add(new BasicNameValuePair(inputName, data));
      httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
      HttpResponse httpResponse = new DefaultHttpClient()
          .execute(httpRequest);
      if (httpResponse.getStatusLine().getStatusCode() != 200) {
        Log.d("HTTP Response:", url);
        Log.d("HTTP Response Code", httpResponse.getStatusLine()
            .toString());
        return false;
      }
    } catch (Exception e) {
      return false;
    }
    return true;
  }
}

   
    
    
    
    
  








Related examples in the same category

1.Http Connection
2.Using HttpGet to get the web response
3.Create Http connection
4.Http connection with
5.HttpGet and DefaultHttpClient
6.Http Post
7.Simple HTTP Request
8.Http Request Class
9.Http Get and Http Post
10.Get Text from HttpResponse
11.Http Request
12.Http Downloader
13.Is Http Url Available
14.Http Retriever
15.Receive Response from HttpURLConnection
16.Print http headers. Useful for debugging.
17.Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/
18.Send message with HttpPost
19.Get Http Stream
20.Generic Object Http Loader
21.Http Get and DefaultHttpClient
22.Gets http output from URL
23.Util for Http Get
24.do Http Get Request and return the status code
25.Http Get
26.implements HttpClient
27.Get File From HTTP
28.Make all redirects to go to http in stead of https
29.New Http Client Manager
30.Http Client Manager
31.Multipart Post
32.Get Server Data
33.Yahoo News Crawler
34.Send Packet
35.Read a web page
36.parse Request Header
37.This class is in charge of synchronizing the events (with due dates) with Google Calendar
38.Update Favicon
39.Converts key-value pair to appropriate signature for Facebook.