[英]Convert curl request to java request
我需要向Google網上商店創建http請求以上傳項目。
我做到了,它奏效了。
curl -H "Authorization: Bearer Mytoken" -H "x-goog-api-version: 2" -X POST -T /Users/mac/Downloads/file_name_3.25.10.zip -v https://www.googleapis.com/upload/chromewebstore/v1.1/items
我想知道如何傳遞-T文件值。 這是我的代碼。
URL url = new URL("https://www.googleapis.com/upload/chromewebstore/v1.1/items");
Map<String, String> params = new HashMap<String, String>();
params.put("FILE",filePath);
Map<String, String> requestPropertys = new HashMap<String, String>();
requestPropertys.put("Authorization","Bearer " +
GoogleWebStoreDeveloperAuthService.getAccess_token());
requestPropertys.put("x-goog-api-version","2");
requestPropertys.put("Accept","*/*");
content = NetworkUtil.crossApplicationRequestPost(url, params, requestPropertys);
公共靜態字符串crossApplicationRequestPost(URL網址,地圖參數,地圖requestPropertys){
String result = null;
String param = getQueryString(params);
param = addHashQuery(param);
/* End preparing params */
byte[] postData = param.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
log.info(" url :"+url);
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
for (Entry<String, T> entry : requestPropertys.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
connection.setRequestProperty(key, value.toString());
}
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length",Integer.toString(postDataLength));
connection.setUseCaches(false);
try (DataOutputStream wr = new DataOutputStream(
connection.getOutputStream())) {
wr.write(postData);
}
log.info(" crossApplicationRequestPost :"+connection.getResponseCode());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
result = IOUtils.toString(inputStream, "UTF-8");
inputStream.close();
} else {
log.severe("try fails. Connect to:" + url.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
在這個StackOverflow問題中,是如何在多部分POST HTTP請求中上載文件的問題的解決方案。
除此之外,我真的建議您使用某種類型的幫助程序來幫助您簡化請求。 它們很多,但是Square的OKHTTP庫是一個受歡迎的(並且有很多文檔)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.