0

I am using the TripIt.com API for a project but I am totally confused about how to convert this CURL command to Java.

$ curl -k -D /dev/tty --data-urlencode xml@/var/tmp/trip.xml --user <username>:<password> https://api.tripit.com/v1/create 
HTTP/1.1 200 OK
Server: nginx/0.6.32
Date: Fri, 05 Dec 2008 22:12:35 GMT
Content-Type: text/xml; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

I know I have to use URLConnection, but don't know how to set other values. Like username, password, path to the XML file etc...

How should I do that?

1

1 Answer 1

1

With HttpUrlConnection it's pretty simple

// setup username/password
Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});


// convert XML data string to bytes
byte[] data = "<yourxml />".getBytes();

// prepare multipart object
MultipartEntity multi = new  MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multi.addPart("uploadedFile", new InputStreamBody(new ByteArrayInputStream(data), "text/xml", "somefile.xml"));

// create your connection
URL url = new URL(url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();

// use POST
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(multi.getContentType().getName(), multi.getContentType().getValue());


//setup header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// ..... others header params .....

// upload file
OutputStream os = conn.getOutputStream();
multi.writeTo(conn.getOutputStream());
os.close();

// perform connection
int responseCode = con.getResponseCode();

// success?
if(responseCode == 200) {
  // read response
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;

  // use your favorite output STREAM
  StringBuffer response = new StringBuffer();

  while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
  }
  in.close();

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.