gpt4 book ai didi

java - 安卓,http : How to upload a file to a site hosted by a shared server?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:53 26 4
gpt4 key购买 nike

我给自己买了一个网站,该网站托管在一台使用 cpanel 共享一个 IP 地址的 linux 服务器上。现在的问题是,我想使用此代码将文件上传到我的网站。每次我使用像 www.site 这样的站点地址时,我都会收到一个异常,提示该 URL 格式错误。当我使用 ip 地址时(因为这是一个共享服务器),我找不到我的 php 代码,因为我不知道如何链接到我的地址。

有谁...有人知道如何将我链接到我的网站,这样我就可以上传一个 xml 文件吗?这里真的需要帮助......

任何帮助将不胜感激,因为我对网络知识一无所知。

    HttpURLConnection connection = null; 
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/data/test.send/testsend.txt";
String urlServer = "http://www.site.com/filefortransfer.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

// Enable POST method
connection.setRequestMethod("POST");

connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
String serverResponseCode = Integer.toString(connection.getResponseCode());
String serverResponseMessage = connection.getResponseMessage();

fileInputStream.close();
outputStream.flush();
outputStream.close();

}
catch (Exception ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
}

最佳答案

在 Android 上,更复杂的 HTTP 网络最好使用 HttpClient 类。

这是一个多部分文件上传的例子:http://rapidandroid.org/wiki/HttpUpload

关于java - 安卓,http : How to upload a file to a site hosted by a shared server?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com