Android - Upload image along with request data - java

I want to upload an image to my server through an android app however I would also like to pass other data along with the image (authentication, intention, etc.).
I have normally been making requests like so:
http://server/script.php?t=authtoken&j_id=12&... etc
However, I assume I cannot simply tack on another query parameter containing the byte array for the image as that would result in a URL with a size on the order of millions of characters.
&image=001101010010110111010001010101010110100101000101010100010... etc
I'm at a loss as to how I should approach this and would appreciate any suggestions. If I am not able to send the data through an http request, how would I handle the incoming data server-side?
Thanks.

Here's how I got it work for those who may find this in the future.
For this example, let's say we want to query the PHP script upload.php on the root of www.server.com with the parameters t=ABC123 and id=12. Along with this request, we also want to upload an image stored in the java.io.File object img. We will also be expecting a response from the server letting us know whether the upload was successful or not.
ANDROID SIDE
On the android side, you will need the following JARs:
apache-mime4j-core-0.7.2.jar
Availabe here and:
httpclient-4.3.1.jar
httpcore-4.3.jar
httpmime-4.3.1.jar
Availabe here.
Here is a snippet on how to make the multipart request and get a response:
public String uploadRequest(String address, File img)
{
HttpParams p = new BasicHttpParams();
p.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient client = new DefaultHttpClient(p);
HttpPost post = new HttpPost(address);
// No need to add regular params as parts. You can if you want or
// you can just tack them onto the URL as usual.
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("image", new FileBody(img));
post.setEntity(builder.build());
return client.execute(post, new ImageUploadResponseHandler()).toString();
}
private class ImageUploadResponseHandler implements ResponseHandler<Object>
{
#Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException
{
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity);
}
}
An example of using this method in the code (assume the variable img has already been declared containing the File object of the image you wish to upload):
// Notice regular params can be included in the address
String address = "http://www.server.com/upload.php?t=ABC123&id=12";
String resp = uploadRequest(address, img);
// Handle response
PHP SIDE
For the server-side script, the text params can be accessed normally through PHP's $_REQUEST object:
$token = $_REQUEST['token'];
$id = $_REQUEST['id'];
And the image that was uploaded can accessed by using the information stored in the PHP $_FILES object (See the PHP docs for more info):
$img = $_FILES['img'];

Related

Rest Assured Automation

How to post request JSON Data and attach file to upload
actually there is a form which contains attachment so how to send request to fill form and attach image file
Response response = given().config(config).header(key, value).header(contentType, "multipart/mixed")
.multiPart("attachment[]", upleadFile).body(jsonBody).when().post(apiURL).then().statusCode(200).extract().response();
I have got solution use this.
In first we are passing exact key like attachment[]
and for other objects
{
Response response =
given().header(key, value).
multiPart("attachment[]", new File("E:/Lightshot/Screenshot_2.png")).
multiPart("issueTypeId", json.get("issueTypeId").toString()).
multiPart("relationJson",json.get("relationJson").toString()).
multiPart("url",json.get("url").toString())
.when().post(apiURL).then().statusCode(200).extract().response();
return response;
}

POST a txt file to remote HTTP server

I am a little lost with this problem and need some help with this. What I need to do is make a post request to an HTTP REST Interface using Java. In this request, I need to send the key as the parameter and need to upload the text file to the server. This file will be locally available.
Nothing here is user input. I am not sure how to upload file to that server In the instruction page this is written
This step requires an HTTP Post request to the URI "someurl.com"
With HTTP Post variable named key and its value
and the in.txt file attached
After making this request I will get an out.txt file as a response.
So far over the internet I found this code which is close
dos.writeBytes(message); //here message is String and dos is DataOutputStream
dos.flush();
dos.close();
But here message is the string, I was wondering if there is a way to sent file to the server.
You can use this method to upload file with some key and value parameters
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("someurl.com");
//Post variable named key and its value
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("id", id, ContentType.TEXT_PLAIN);
builder.addTextBody("apd", apd, ContentType.TEXT_PLAIN);
//path of file
String filepath = "C:\Users\Downloads\images\file.txt";
// This attaches the file to the POST:
File f = new File(filepath);
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Guys thank you for your answers but they didn't worked for me. I don't have much experience with API of this sort. In the help section, I found to use curl and was able to successfully get the results. Here is the code I used
String[] command = {"curl","-H","key:keyValue","-F","file=#in.txt",
"http://example.com/evaluate.php ","-o","output.txt"};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
p = process.start();
Yes in the massage parameter you need to Serialize your file - convert it to bytes, encrypt it. Then send it as a message. Then decrypt and build your file from the bytes on the other side

Send xml as part of URL request in Java

This might be a trivial question but I'm trying to send web request to USPS to get a http post response (or email response depending on my request) containing the tracking information based on the tracking number that I send in. The documentation says the xml needs to appended as part of the url like below
http://secure.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<PTSEmailRequest USERID="xxxxx"><TrackId>xxxxx</TrackId><RequestType>EN</RequestType></PTSEmailRequest>
I saw there were 2 ways to make an xml request, one using HttpPost and the other URLConnection. I'm a bit thrown by how I go about this and I'm failing to appreciate what's the difference between appending xml in the url and a normal http request. Can someone please clear things up for me?
USPS documentation for tracking =>
https://www.usps.com/business/web-tools-apis/track-and-confirm.pdf
I read these related Stackoverflow posts
Java: How to send a XML request?
posting XML request in java
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://secure.shippingapis.com/ShippingAPITest.dll");
List<String> params = new ArrayList<String>(2);
params.add(new BasicNameValuePair("API", "TrackV2"));
params.add(new BasicNameValuePair("XML", FuncTOGenerateXML()));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
//.....
// .....
instream.close();
}
An HTTP request can use one of several methods, like POST, GET, DELETE, PUT... Here we talk about POST and GET
Technical differences
With GET, the data is retrieved from the parameters in the URL.
With POST, the data is retrieved from the data transmitted inside the HTTP message.
Intended use differences
GET is intended to be used when the request does not cause a change (v.g., searching in Google). Since you can repeat the request without side effects, the data is in the URL and can be stored in the browser history, favorites, etc.
POST is intended to use when you are performing a change (v.g. sending an e-mail, doing a on-line purchase). The data related is not stored with the URL (it is then that, if you go back to a page that was obtained using POST, the browser many times will show you a pop-up asking for permission to send the data again.
In real usage, the distinction is not so clear cut, in particular POST is sometimes used when the data is too large (URLs have limited length). Also, sometimes GET is used with the meaning of POST so the data can be presented as an HTML link.
Finally, URLConnection is the basic API for opening a connection (which you can use as a POST or GET request, based in how you pass the data, or something else) and HttpPost is just a higher level API for creating a POST request. If you go the basic way, use HttpURLConnection better.

google-http-java-client json update existing object

i'm trying to use google-http-java-client on android and parse JSON responses from my server.
do do that i'm using the following code (provided by the examples of the project)
private static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
HttpRequestFactory requestFactory = HTTP_TRANSPORT
.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url + paramsList));
HttpResponse response = request.execute();
and everything works fine for new objects with
result = response.parseAs(PxUser.class);
but i need to update an existing object with the data from the json string.
with jackson only i can use the following code but with the google client i cannot find any solution.
InputStream in = -get-http-reponse-
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(MySingleton.getInstance());
reader.readValue(InputStream in);
so i need a way to update an existing object just like with this jackson example but by using the client.
is there a way? do i have to use jackson-databind.jar? how can i accomplish this?
thanks in advance
PS: i can switch to gson if its needed, no problem
It depends on whatever endpoint is receiving the API call, and what it expects the request to look like.
The Google HTTP Java Client simply handles the processes like making the call, encoding and decoding an object, exponential backoff, etc for you. It's up to you to create the request that does what you want and how the server expects it to look.
Likely, the API you're making the request to expects an object update to be made with a PUT request. The updated object is likely going to be the content of the request, encoded in some specific format. Let's assume JSON, since you're parsing JSON responses. So for the purpose of example, let's say you're going to request an object, modify it, then send it back.
First, you get the resource and parse it into your object:
PxUser myUser = response.parseAs(PxUser.class);
Then you modify the object somehow
myUser.setName("Frodo Baggins");
Now you want to send it back to the server as a JSON object in a PUT request:
// httpbin.org is a wonderful URL to test API calls against as it returns whatever if received.
GenericUrl url = new GenericUrl("http://httpbin.org/put");
JsonHttpContent content = new JsonHttpContent(new JacksonFactory(), myUser);
HttpRequest request = requestFactory.buildPutRequest(url, content);
HttpResponse response = request.execute();
System.out.println(response.parseAsString());
The specifics of how you encode and update your content is totally up to you and the API's specification. This is especially easy if you're creating the server receiving the call too.
If you're working with a preexisting API, you may want to update the question with the
specific problem (API "x" requires a response that looks like Blah; how do I do that in the google-http-java-client).
If you're working with a Google API, you'll want to be using the google-api-java-client which does all of this work for you.

Stream HTTP GET response to file in Mule

How do you make a HTTP GET request in Mule, and then stream the response to a file? My application stores the entire response in memory, but the response can be large, so this needs to be fixed. I want to save the response to a temporary file, and then stream the file contents back to the client.
Right now, I'm doing:
String restUrl = "http://www.url.com";
UMOEventContext context = RequestContext.getEventContext();
GetMethod method = new GetMethod(restUrl);
UMOMessage muleMessage = new MuleMessage(method);
muleMessage.setProperty(RestServiceWrapper.REST_SERVICE_URL, restUrl);
UMOMessage result = context.sendEvent(muleMessage, new MuleEndpointURI("vm://identifier")); //OutOfMemoryException
String body = result.getPayloadAsString();
I'm using Mule 1.3.3 and cannot upgrade. Thank you.

Categories

Resources