如何将cURL命令转换为HTTP POST?

时间:2018-04-14 16:19:33

标签: android curl http-post

是否有人能够帮助将以下cURL命令转换为可以通过Android应用程序上的按钮单击运行的HTTP POST?

cURL命令:

'C:\\DevPrograms\\curl-7.59.0-win32-mingw\\bin\\curl.exe' -X POST --data-binary '@C:\xampp\htdocs\Pastec_Test_Connection\Test_Images\Test_FiveHundredEuro01.jpg' 'http://localhost:4212/index/searcher'

1 个答案:

答案 0 :(得分:0)

以下是代码:

  • 将JPG加载为位图。
  • 将位图转换为字节数组。
  • 使用字节数组通过HttpURLConnection发送POST。
  • 从服务器获取响应。
Bitmap bitmap = null;
Uri uri = Uri.fromFile(new File("C:/xampp/htdocs/Pastec_Test_Connection/Test_Images/Test_FiveHundredEuro01.jpg"));
InputStream stream = null;

try {
    stream = getContentResolver().openInputStream(uri);
    BitmapFactory.Options options = new BitmapFactory.Options();
    bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (IOException e) {
    Log.e("IOException", e.getMessage(), e);
    return null;
} finally {
    try {
        if (stream != null) stream.close();
    } catch (Exception e) {}
}
ByteArrayOutputStream byteStream = null;
byteStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
// Convert ByteArrayOutputStream to byte array. Close stream. 
byte[] byteArray = byteStream.toByteArray();
byteStream.close();
byteStream = null;

URL url = null;
try {
    url = new URL("http://localhost:4212/index/searcher");
} catch (MalformedURLException e) {
    e.printStackTrace();
}
HttpURLConnection conn = null;
try {
    conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
    e.printStackTrace();
}
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
try {
    conn.setRequestMethod("POST");
} catch (ProtocolException e) {
    e.printStackTrace();
}
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(byteArray.length));
conn.setUseCaches(false);
try {
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream()) {
        wr.write(byteArray);
        wr.flush();
        wr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    System.out.println(response.toString());