-1

how can I transfer this Curl command to Java http post:

curl --insecure -XPOST -H 'Authorization: XXXXX' -F 'Name=test name' -F 'text=test content123456' 'http://serverhost.com/api/index.php?action=send'

Thanks guys.

I've already try,but I think there may have a better way.

URL url = new URL(reqUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("X-Requested-With", "Curl");
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Authorization", authorization);

OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(reqBody);
out.flush();
out.close();
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39
tony yong
  • 1
  • 1
  • I think this [answer](https://stackoverflow.com/a/2026299/2814332) might help you. – user2814332 Jul 12 '19 at 11:20
  • Well this is wrong: `urlConnection.setRequestProperty("X-Requested-With", "Curl");` You are not using `Curl` to send the request. But why don't tell us what is causing you difficulties. Right now, this question comes across as "please write the rest for me". – Stephen C Jul 12 '19 at 12:44
  • Thank guys.I already change my method.Pls see my answer below. – tony yong Jul 15 '19 at 07:26

1 Answers1

0

Thanks guys.I already fixed it. Code example down bleow: URL url = new URL(urlStr);

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);

conn.setReadTimeout(30000);

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

//advance api if (!TextUtils.isEmpty(authorization)) {

conn.setRequestProperty("Authorization", authorization);

}

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("User-Agent",

    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

conn.setRequestProperty("Content-Type",

    "multipart/form-data; boundary=" + BOUNDARY);

out = new DataOutputStream(conn.getOutputStream());

// text if (textMap != null) {

StringBuffer strBuf = new StringBuffer();

Iterator iter = textMap.entrySet().iterator();

while (iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();

    String inputName = (String) entry.getKey();

    String inputValue = (String) entry.getValue();

    if (inputValue == null) {

        continue;

    }

    strBuf.append("\r\n").append("--").append(BOUNDARY)

            .append("\r\n");

    strBuf.append("Content-Disposition: form-data; name=\""

            + inputName + "\"\r\n\r\n");

    strBuf.append(inputValue);

    logger.info(inputName + "," + inputValue);

}

out.write(strBuf.toString().getBytes());

}

tony yong
  • 1
  • 1