我正在为项目使用TripIt.com API,但对于如何将此CURL命令转换为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


我知道我必须使用URLConnection,但是不知道如何设置其他值。如用户名,密码,XML文件的路径等...

我应该怎么做?

最佳答案

有了HttpUrlConnection,它非常简单

// 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();

}

10-07 17:42