Skip to content

Instantly share code, notes, and snippets.

@oguya
Last active January 3, 2016 00:28
Show Gist options
  • Save oguya/8382477 to your computer and use it in GitHub Desktop.
Save oguya/8382477 to your computer and use it in GitHub Desktop.
upload file in java to server side php
public static void uploadFile(String filePath, String serverURL) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
//post request to send file
HttpPost httpPost = new HttpPost(serverURL);
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
FileBody uploadFile = new FileBody(new File(filePath));
MultipartEntity reqEntity = new MultipartEntity();
// reqEntity.addPart("the args. the server takes", uploadFile);
reqEntity.addPart("uploaded_file", uploadFile);
httpPost.setEntity(reqEntity);
//debugging
System.out.println("request: " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
//debugging
System.out.println("status line: " + response.getStatusLine());
if (httpEntity != null) {
System.out.println("server Response: " + EntityUtils.toString(httpEntity));
httpEntity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment