使用HttpURLConnection在java中编程curl

时间:2014-08-07 14:02:45

标签: java curl httpurlconnection

我正在尝试在java中发送以下curl命令: 卷曲-v -XPOST -u" 7a33f0:" http://geras.1248.io/series/santander/bus3025 --header" Content-Type:application / json" -d@bus3025.json

public boolean writeSeries(String urlstr, String data){
    try {
        // POST
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        System.out.println("POSTING");
        URL url = new URL(urlstr);
        String user = "7a33f0:";
        String encoded = new String(Base64.encodeBase64(user.getBytes()));

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Authorization", String.format("Basic %s", encoded));
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Content-Length",  Integer.toString(data.getBytes().length));
        connection.setRequestMethod("POST");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(data);
        writer.flush();
        writer.close();

        int responseCode = connection.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + data);
        System.out.println("Response Code : " + responseCode);

        System.out.println(connection.getContentType());
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                content));
        String line;
        while ((line = in.readLine()) != null) {
            pw.println(line);
        }
        } catch (MalformedURLException e) {
        // ...
        } catch (IOException e) {
        // ...
        }
    return true;
}

但是,我收到了401响应代码(未经授权)。

发送' POST'请求网址:http://geras.1248.io/series/santander/bus3024 发布参数:bus3024.json 回复代码:401 如何设置-u参数?谢谢你的帮助。

0 个答案:

没有答案