I am trying to upload any file from Java Console application to ASP.NET MVC web application.
For this, I am using Apache HttpClient library.
ConsoleApplication.java
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:52031/home/DataPost");
File file = new File("A.txt");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "multipart/form-data");
mpEntity.addPart("file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
httpclient.getConnectionManager().shutdown();// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder builder=new StringBuilder();
while ((line = rd.readLine()) != null)
{
builder.append(line);
}
System.out.println(builder.toString());
ASP.NET HomeController.cs
[HttpPost]
public string DataPost(HttpPostedFile file)
{
return file.FileName.ToString();
}
I carefully debugged the above code and found out that java program properly accessing DataPost method, but could not upload the file as file parameter is null in the method.
I google about it and found some stackoverflow questions on java httpclient, but none of the questions are about server side implementation.
Please let me know, where I am doing wrong.
Thanks
Related
I am creating an application where I need to get file attached in mail and then send that complete file as input of another API of portal called 'asana'. I don't want to save/ download the file locally.
I referred this site to get the attached file through mail.
But, I need to send the file to 'asana' API without downloading it.
Here is the code of asana API to send file through API.
String url = "https://app.asana.com/api/1.0/tasks/"+asanaActivitiesDto.getTaskId()+"/attachments";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Bearer " + asanaActivitiesDto.getBearerToken());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("task", jsonInput.get("taskId").toString(), ContentType.TEXT_PLAIN);
// now here I actually want file from attachment of the mail
// currently taking file from local for testing
File f = new File(asanaActivitiesDto.getFile());
builder.addBinaryBody(
"file",
//Here, as a second input, I need to set file from the
//attachment of the mail
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
post.setEntity(multipart);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
JSONParser parser = new JSONParser();
jsonOutput = (JSONObject) parser.parse(result.toString());
at the place of new FileInputStream(f), I need to send file attached to that mail. What are the possible ways to do the same?
You can just read the data in the email attachment as an InputStream. Try something like:
mbp = // the MimeBodyPart containing the attachment
builder.addBinaryBody(
"file",
mbp.getInputStream(),
ContentType.APPLICATION_OCTET_STREAM,
mbp.getFileName()
);
i want to upload a file to server php using post
Heres my code
String url = "http://blabla.com/upload.php";
File file = new File(Environment.getExternalStorageDirectory(),
"Myfile.log");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
}
My question is how can i handle it on php ? If its in $_FILES array then what id i should use to put it in uploads folder ($_FILES['whatShouldBeHere'] )? Thanks .
I have a java program which makes an http post request to a php script on my website. Here is the code. I am also using the new Apache HTTP Components API. Here is a link to the download -> http://hc.apache.org/downloads.cgi
public static void main(String args[]) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://ftstoo.com/public_html/TheFinalTouchSecurity/Database/test.php");
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("name", "Cannon"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
// Get the HTTP Status Code
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Get the contents of the response
InputStream in = resEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
}
}
My test.php file is located at http://ftstoo.com/public_html/TheFinalTouchSecurity/Database/test.php
Here is my php code.
<?php
$name = $_POST['name'];
echo "Success, . $name . !";
?>
The output I am getting when I run the java program is the html from a redirecting page on my website that says the page does not exist. I want the output to return a string that says "Success, Cannon!" I think there are probably several things I am doing wrong, but if someone could please give me a hand I would really appreciate it!
curl -F file=#/path/to/index.html -u lslkdfmkls#gmail.com -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps
I am trying to achieve the same using a java program using HttpClient library.
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("build.phonegap.com", 443, "https");
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort(),AuthScope.ANY_REALM),
new UsernamePasswordCredentials("abc#gmail.com", "abc123"));
String authToken = "?auth_token=abcdefgh";
HttpPost httpPost = new HttpPost("https://build.phonegap.com/api/v1/apps" + authToken );
String jsonString = "{\"title\":\"API V1 App\",\"create_method\":\"file\"}";
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart(new FormBodyPart("data", new StringBody(jsonString)));
multipartEntity.addPart("file", new FileBody(new File("C:/Users/Desktop/app.zip")));
/*StringEntity entity = new StringEntity(jsonString, "UTF-8"); */
httpPost.setEntity(multipartEntity);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println(httpResponse.getStatusLine());
if(entity != null ){
System.out.println(EntityUtils.toString(entity));
}
In the above code I can only set StringEntity or FileEntity but not both and I think this is what is required to get the functionality of the curl command.
After trying with StringEntity and FileEntity I tried with MultipartEntity but no luck..
Can you please provide me with more details and if possible an example..
Thanks in advance.
One has to instantiate the MultipartEntity as follows:
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE
) ;
This worked for me.
By default the MultipartEntity is instantiated with HttpMultipartMode.STRICT mode which is documented in the javadocs as "RFC 822, RFC 2045, RFC 2046 compliant" .
Can someone brief out the RFC's mentioned here for clear understanding..
Thanks a Lot
So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());