gpt4 book ai didi

java - 无法使用 HttpPost 上传文档

转载 作者:行者123 更新时间:2023-11-29 03:30:35 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将文档从我的本地计算机上传到 Http,但我收到 HTTP 400 Bad request 错误。我的源数据在 Json 中。

URL url = null;
boolean success = false;

try {
FileInputStream fstream;
@SuppressWarnings("resource")
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test.txt"));
StringBuffer buffer = new StringBuffer();
String line = null;

while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}

String request = "http://example.com";
URL url1 = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setDoOutput(true); // want to send
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false); // no user interaction
connection.setRequestProperty("Content-Type", "application/json");


DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.flush();
wr.close();
connection.disconnect();


System.out.println(connection.getHeaderFields().toString());

// System.out.println(response.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最佳答案

查看 apache http 库,这将对此有很大帮助:

File file = new File("path/to/your/file.txt");
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://someposturl.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}

} catch (Exception e) {
e.printStackTrace();
}

上面的例子取 self 的blog它应该可以与标准的 Java SE 和 Android 一起使用。

关于java - 无法使用 HttpPost 上传文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18480714/

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