0

Hi I am uploadingfile to php server.For this we require to send string parameter .I am using following code for uploading.So is there any tutorial that set parameter or any explanation that describes setting .thanks url = new URL(httpPath);

    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);
bharath
  • 13,880
  • 16
  • 53
  • 93
kehnar
  • 1,351
  • 1
  • 12
  • 25
  • possible duplicate of [How to use java.net.URLConnection to fire and handle HTTP requests?](http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests) – Matt Ball Aug 27 '11 at 14:29

1 Answers1

1

Don't reinvent the wheel. Use Apache HttpClient. Read this javadoc page for an example of a post containing a file upload and a string parameter:

  File f = new File("/path/fileToUpload.txt");
  PostMethod filePost = new PostMethod("http://host/some_path");
  Part[] parts = {
      new StringPart("param_name", "value"),
      new FilePart(f.getName(), f)
  };
  filePost.setRequestEntity(
      new MultipartRequestEntity(parts, filePost.getParams())
      );
  HttpClient client = new HttpClient();
  int status = client.executeMethod(filePost);
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
  • Thanks for quick reply.I want to used in android .Does it works. thanks – kehnar Aug 27 '11 at 14:35
  • You should have tagged your question with android. Android bundles the apache HttpClient, but without this class. Nevertheless, it seems that it's easy enough to add it. Read the following Google groups post: http://groups.google.com/group/android-developers/msg/1ea124b384da9dc2. You'll need to use the mime4j and httpmime libraries. – JB Nizet Aug 27 '11 at 14:47