将curl请求转换为java请求

时间:2017-11-15 14:52:10

标签: java file curl httpurlconnection

我需要为谷歌网上商店创建http请求以获取上传项目。

我是用curl做的,但它确实有效。

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

public static String crossApplicationRequestPost(URL url,Map params,Map 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;
}

1 个答案:

答案 0 :(得分:0)

this StackOverflow question中解决了如何在多部分POST HTTP请求中上传文件的问题。

除此之外,我建议您使用某种类型的帮助程序来帮助您更轻松地处理请求。它们很多,但是一个受欢迎的(并且有很多文档)是Square's OKHTTP library