Jackson Unhandled Exception? - java

I am new to android programming, and I was following this tutorial
to create a GCM server program. However, I came across a frustrating bug and would greatly appreciate any help.
This is my POST2GCM class:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;
public class POST2GCM extends Content {
private static final long serialVersionUID = 1L;
public static void post(String apiKey, Content content){
try{
// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");
// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. Specify POST method
conn.setRequestMethod("POST");
// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
// 5. Add JSON data into POST request body
//`5.1 Use Jackson object mapper to convert Contnet object into JSON
ObjectMapper mapper = new ObjectMapper();
// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
// 5.3 Copy Content "JSON" into
mapper.writeValue(wr, content);
// 5.4 Send the request
wr.flush();
// 5.5 close
wr.close();
// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 7. Print result
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have included the "jackson-databind-2.5.1.jar" file but I get the error:
Unhandled Exception: com.fasterxml.jackson.databind.JsonMappingException
on the line mapper.writeValue(wr, content);
What is causing this exception, and how can I fix it?

jackson-databind is a general data-binding package which works on streaming API (jackson-core) implementations. That's why you need to add jackson-core and catch 3 exceptions. writeValue method throws IOException, JsonGenerationException and JsonMappingException.
try {
mapper.writeValue(wr, content);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope it will be useful for you.

Related

Use java code with REST methods to Send XML Request and Read XML Response from API (Insomnia / SoapUI)

Overview of goals: (1) save XML file to a string element in IntelliJ (2) send the request XML to an http endpoint (3) get the response XML from the http endpoint
So far I have been able to read the XML response but keep receiving errors on my attempts to send a request. I have working methods not implementing the REST methods but would prefer to use those for my project. It's a bit of a rudimentary approach as I am still learning so any tips are greatly appreciated. Would like to be closer to the
My attempts so far have been to set the xml request as a string to send to the endpoint and then read the response from that same endpoint. Below is the code I have attempted that does not yet rely heavily on the REST method. Whenever I try to send the request, I get an error that this method is not allowed. Are there suggestions on my current code I can edit to get this request working?
package com.tests.restassured;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class VIVPXMLResponseTest {
public static void main(String[] args) {
VIVPXMLResponseTest vivpXMLResponseTest = new VIVPXMLResponseTest();
vivpXMLResponseTest.getXMLResponse("Success");
}
public void getXMLResponse(String responseCode) {
String wsURL = "http://localhost:8080/hello/Hello2You";
URL url = null;
URLConnection connection = null;
HttpURLConnection httpConn = null;
String responseString = null;
String outputString = "";
ByteArrayOutputStream bout = null;
OutputStream out = null;
InputStreamReader isr = null;
BufferedReader in = null;
String xmlInputRequest = "<pasteXMLrequestHere>";
try {
url = new URL(wsURL); // create url object using our webservice url
connection = url.openConnection(); // create a connection
httpConn = (HttpURLConnection) connection; // cast it to an http connection
byte[] buffer = new byte[xmlInputRequest.length()]; // xml input converted into a byte array
buffer = xmlInputRequest.getBytes(); // put all bytes into buffer
String SOAPAction = "";
//Set the appropriate HTTP parameters
httpConn.setRequestProperty("Content-Length", String
.valueOf(buffer.length));
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
//httpConn.setRequestMethod("GET");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
out = httpConn.getOutputStream();
out.write(buffer); // write buffer to output stream
out.close();
//Read response from the server and write it to standard out
isr = new InputStreamReader(httpConn.getInputStream()); //use same http connection, call getInputStream
in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) //read each line
{
outputString = outputString + responseString; //put into string -- may need to change if long file
}
System.out.println(outputString); //print out the string
System.out.println(" ");
//Get response from the web service call
Document document = parseXmlFile(outputString); //parse the XML - gets back raw XML - returns as document object model
NodeList nodeLst = document.getElementsByTagName("ns:Code"); //where success / failure response is written
NodeList nodeLst2 = document.getElementsByTagName("ns:Reason"); //where success / failure response is written
String webServiceResponse = nodeLst.item(0).getTextContent();
String webServiceResponse2 = nodeLst2.item(0).getTextContent();
System.out.println("*** The response from the web service call is : " + webServiceResponse);
System.out.println("*** The reason from the web service call is: " + webServiceResponse2);
} catch (Exception e) {
e.printStackTrace();
}
}
private Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //get document builder factory
DocumentBuilder db = dbf.newDocumentBuilder(); //create new document builder
InputSource is = new InputSource(new StringReader(in)); //pass in input source from string reader
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
I'd like to be closer to this format
#Test
#RestAssuredMethod(config = "src/test/resources/config/sampleRest.json")
public void getResponse() throws IOException {
Response response3 = given().log().all()
.when().get("updateFiles/")
.then().assertThat()
.statusCode(HttpStatus.SC_OK) //SC_OK = 200
.body("status[0].model", equalTo("Success"))
.header("Content-Type", containsString("application/json"))
.log().all(true)
.extract().response();
String firstResponse = response3.jsonPath().get("status[0].model");
asserts.assertEquals(firstResponse, "SUCCESS", "Response does not equal SUCCESS");
List allResponses = response3.jsonPath().getList("status[0].model");
System.out.println("**********" + favoriteModels);
asserts.assertTrue(allResponses.contains("Success"), "There are no success responses");
}
Edit: Here is my working send / receive response that I am trying to integrate into using full REST methods:
package com.chillyfacts.com;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Send_XML_Post_Request {
public static void main(String[] args) {
try {
String url = "<enterEndpointHere>";
URL obj = new URL(url);
HttpURLConnection HTTPConnection = (HttpURLConnection) obj.openConnection();
HTTPConnection.setRequestMethod("POST");
HTTPConnection.setRequestProperty("Content-Type","text/xml; charset=utf-8");
HTTPConnection.setDoOutput(true);
String xml = "<pasteXMLRequestHere>"
DataOutputStream writeRequest = new DataOutputStream(HTTPConnection.getOutputStream());
writeRequest.writeBytes(xml);
writeRequest.flush();
writeRequest.close();
String responseStatus = HTTPConnection.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(
HTTPConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("\n **** RESPONSE FROM ENDPOINT RECEIVED ****: \n\n" + response.toString() + "\n\n *************** END OF RESPONSE *************** \n");
} catch (Exception e) {
System.out.println(e);
}
}
}

I want to get result json from goeuro api

I am developing API in java to get json from GoEuro API is available at github. i want to know parameter i need to send with POST method and get result as json and combined with my custom logic.
Here is my java code to call api.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JsonEncodeDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search?departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am not good in nodejs. Any Help would be appreciated.
First of all the url needs to be only this http://www.goeuro.com/GoEuroAPI/rest/api/v3/search
Then you need to add parameters using params in request.
Your if response != 200 has to be after you make the request.
public static void main(String[] args) {
try {
URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = "departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
However, i found my answers from github issue.
Here are required params and there expected json format.
{
"arrivalPosition":{
"positionId":380244
},
"currency":"EUR",
"departurePosition":{
"positionId":380553
},
"domain":"com",
"inboundDate":"2017-04-19T00:00:00.000",
"locale":"en",
"outboundDate":"2017-04-18T00:00:00.000",
"passengers":[
{
"age":18,
"rebates":[]
}
],
"resultFormat":{
"splitRoundTrip":true
},
"searchModes":[
"directbus"
]
}

Android HTTPUrlConnection SocketTimeoutException/Indefinite Hang?

I'm working on an Android app for a client, and I'm calling their API to get the info for various parts of my app. There is one call that results on SocketTimeoutException if I set a timeout, or infinitely hangs if I don't; however, it works just fine on the web client(React), so it can't be the server.
Code:
package io.voluntu.voluntu;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class SendApproveHours extends AsyncTask<Bundle, Void, String>{
private StringBuilder sb = new StringBuilder();
private String result;
private ApproveHours approveHours;
public SendApproveHours(ApproveHours approveHours){
this.approveHours = approveHours;
}
protected String doInBackground(Bundle... params){
Bundle b = params[0];
String jwt = b.getString("JWT");
System.out.println(jwt);
boolean approve = b.getBoolean("APPROVE");
int[] id = b.getIntArray("ID");
try {
URL url = new URL("http://voluntu.io/api/hour/update");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(2500 /* milliseconds */); //if i don't do this, it will hang indefinitely
httpURLConnection.setReadTimeout(1500 /* milliseconds */);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Host", "voluntu.io");
httpURLConnection.setRequestProperty("Origin", "http://voluntu.io");
httpURLConnection.setRequestProperty("Referer", "http://voluntu.io/hours/approve");
httpURLConnection.setRequestProperty("Cookie", "sessionJWT=" + jwt);
httpURLConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("approveOrReject", approve);
jsonObject.put("hourIDs", Arrays.toString(id));
System.out.println(jsonObject);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
int HttpResult = httpURLConnection.getResponseCode(); //hangs here
System.out.println("HTTP RESULT: " + HttpResult);
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), "utf-8"
));
String line;
while((line = in.readLine()) != null){
sb.append(line);
}
in.close();
}
System.out.println("RESPONSE: " + sb.toString());
httpURLConnection.disconnect();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace();
}
return sb.toString();
}
protected void onPostExecute(String result){
approveHours.refreshHours();
}
}
It hangs on getting the HTTP response code for some reason. I checked the headers and body and they are identical to what the web version is sending, so I have no idea why it's not working. Also, calling other parts of their API works just fine, and in fact this code is mostly copy pasted from other parts of my app that call the API. Help is appreciated!
I fixed it. Instead of an array, you must use JSONArray, or the array gets wrapped in quotes when it gets put in the JSON object.

How to build RESTful request over in java

I tried to understand how to send REST request to server. If I have to implement this as a request in java using httpconnections or any other connections, how would I do that?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
How should this be structured in a standard way?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
There are many options, Apache HTTP client (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) is one of them (and makes things very easy)
Creating REST requests can be as easy as this (using JSON in this case):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
Update: Sorry the link to the documentation was updated.Posted the new one.
you should use json here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
more over it browse link
There are several ways to call a RESTful service with Java but it's not required to use raw level APIs ;-)
It exists some RESTful frameworks like Restlet or JAX-RS. They address both client and server side and aim to hide the technical plumbing of such calls. Here is a sample of code describing how to do your processing with Restlet and a JSON parser:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
You can notice that in the previous snippet, headers Content-type, Date are automatically set for you based on what you sent (form, JSON, ...)
Otherwise a small remark, to add an element you should use a method POST on the element list resource (http://myownHost/resources/) or a method PUT if you have the unique identifier you want to use to identify it (http://myownHost/resources/1). This link could be useful to you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you,
Thierry

Send image file using java HTTP POST connections

I'm trying to send an image to a website using Java HTTP POST requests.
I'm using the base code used here Upload files from Java client to a HTTP server:
This is my modification:
String urlToConnect = "http://localhost:9000/upload";
File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"picture\"; filename=\"bla.jpg\"");
writer.println("Content-Type: image/jpeg");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload)));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
I get a 200 response code in the end, but the image is buggy, as in, random colors, which make me think it's an error in character encoding. I tried using UTF-8 as in the original example, but that just creates a corrupt image.
I am also 100% sure it's not a serverside problem, because I can use rest clients such as Advanced Rest Client/Postman and they can send an image with no problems.
Can you help me pinpoint what's wrong? Thank you.
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class PostFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9000/upload");
File file = new File("C:\\Users\\joao\\Pictures\\bla.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
Use HttpClient to work out this code. Its always better to use stable libraries other than handling from scratch, unless there is something to be handled in custom way.
Today I run into the same issue, I wrote a little nodejs server supports just two routes, upload and download images.
Client should be a java class which sends a images payload via HTTP POST multipart/form-data standard to the server.
If you would like to know why HTTP POST multipart/form-data, please check out the answer from Ciro Santilli from this post: What does enctype='multipart/form-data' mean?
Luckily I found this nice and really good example code:
https://www.techcoil.com/blog/how-to-upload-a-file-via-a-http-multipart-request-in-java-without-using-any-external-libraries/
It shows how we can build up the payload of an multipart http body manuelly without any external lib, only little limitation from my perspective is, that it only handle a mulitpart body with one file.
Because I had no HTML page to sniff the generated POST payload, I used python to generate it and sniff it via wireshark.
Python3 code:
import requests
posturl = 'http://<server>:<port>/<path>'
files = {'image' : open('<file>', 'rb')}
r = requests.post(posturl, files = files)
Just for note: if we define the parameter files from the requests lib with an dict, it generates an mulipart/form-data content.
http://docs.python-requests.org/en/master/user/advanced/#post-multiple-multipart-encoded-files
Wireshark shows everything very clear and finally I ended up with this for sending java:
HttpURLConnection conn =
(HttpURLConnection) new URL("http://<server>:<port>/<path>")).openConnection();
// some arbitrary text for multitext boundary
// only 7-bit US-ASCII digits max length 70
String boundary_string = "some radom/arbitrary text";
// we want to write out
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary_string);
// now we write out the multipart to the body
OutputStream conn_out = conn.getOutputStream();
BufferedWriter conn_out_writer = new BufferedWriter(new OutputStreamWriter(conn_out));
// write out multitext body based on w3 standard
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
conn_out_writer.write("\r\n--" + boundary_string + "\r\n");
conn_out_writer.write("Content-Disposition: form-data; " +
"name=\"image\"; " +
"filename=\""+ <File class instance>.getName() +"\"" +
"\r\n\r\n");
conn_out_writer.flush();
// payload from the file
FileInputStream file_stream = new FileInputStream(<File class instance>);
// write direct to outputstream instance, because we write now bytes and not strings
int read_bytes;
byte[] buffer = new byte[1024];
while((read_bytes = file_stream.read(buffer)) != -1) {
conn_out.write(buffer, 0, read_bytes);
}
conn_out.flush();
// close multipart body
conn_out_writer.write("\r\n--" + boundary_string + "--\r\n");
conn_out_writer.flush();
// close all the streams
conn_out_writer.close();
conn_out.close();
file_stream.close();
// execute and get response code
conn.getResponseCode();
To get the response from the POST just read the input stream accessed via getInputStream(), code snipped in the link.
Reader/Writer classes are designed to handle text data, while images are binary. You need to interpret your files as binary:
FileChannel in = new FileInputStream(fileToUpload).getChannel();
WritableByteChannel out = Channels.newChannel(connection.getOutputStream());
in.transferTo(0, fileToUpload.size(), out)
Of course, you still need to close all opened resources.
Try that:
private DefaultHttpClient mHttpClient;
Context context;
public String error = "";
//Contrutor para que metodos possam ser usados fora de uma activity
public HTTPconector(Context context) {
this.context = context;
}
public HTTPconector() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
}
public void FileClientPost(String txtUrl, File file){
try
{
error = "";
HttpPost httppost = new HttpPost(txtUrl);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Image", new FileBody(file));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
}
catch (Exception e)
{
Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e);
e.getStackTrace();
error = e.getMessage();
}
}
//Verifica se a rede esta disponível
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public String Get(String txtUrl){
try {
URL url = new URL(txtUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
return readStream(con.getInputStream());
} catch (ProtocolException e) {
e.printStackTrace();
return "ERRO: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "ERRO: "+e.getMessage();
}
}
public String Post(String txtUrl){
File image;
try {
URL url = new URL(txtUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//con.getOutputStream().write( ("name=" + "aa").getBytes());
return readStream(con.getInputStream());
} catch (ProtocolException e) {
e.printStackTrace();
return "ERRO: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "ERRO: "+e.getMessage();
}
}
//Usado para fazer conexão com a internet
public String conectar(String u){
String resultServer = "";
try {
URL url = new URL(u);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
resultServer = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
resultServer = "ERRO: "+ e.getMessage();
}
Log.i("HTTPMANAGER: ", resultServer);
return resultServer;
}
//Lê o resultado da conexão
private String readStream(InputStream in) {
String serverResult = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
serverResult = reader.toString();
} catch (IOException e) {
e.printStackTrace();
serverResult = "ERRO: "+ e.getMessage();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
serverResult = "ERRO: "+ e.getMessage();
}
}
}
return serverResult;
}
private class PhotoUploadResponseHandler implements ResponseHandler<Object>
{
#Override
public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.d("UPLOAD", responseString);
return null;
}
}
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
public void fileClientPost(){
HttpClient httpClient = HttpClientBuilder.create().build();
BasicHttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("...", "...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpEntity entity = (HttpEntity) builder.addPart("file", new FileBody(new File("image.jpg")));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
}

Categories

Resources