gpt4 book ai didi

android - 需要在android中使用HttpPost上传文件

转载 作者:行者123 更新时间:2023-11-30 04:06:22 24 4
gpt4 key购买 nike

I would like to upload a name.txt file without ussing MultiEntitiy "importing a large file" as my file is small in size... I have written the following code but unable to upload a file.. thanks for your concern...

URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("userfile", strEmailAddress + ".txt");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("Content-Disposition: form-data; name=\"paramName\"");
Helper.printLogD(" connection " + conn.getContent().toString());

String temp = getStringFromInputStream(conn.getInputStream());
Helper.printLogI("temp" + temp);

最佳答案

我使用以下代码:

public static JSONObject uploadImageToServer(String url, String path,
String usuario) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);

try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userfile", path));
nameValuePairs.add(new BasicNameValuePair("tmp_name", usuario));

for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName()
.equalsIgnoreCase("userfile")) {
// If the key equals to "image", we use FileBody to transfer
// the data
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
// Normal string data
entity.addPart(
nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
}

httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost, localContext);

HttpEntity responseEntity = response.getEntity();

if (responseEntity != null) {
InputStream instream = responseEntity.getContent();
String resultString = convertStreamToString(instream);
instream.close();
// Transform the String into a JSONObject
JSONObject jsonObjRecv = null;
try {
jsonObjRecv = new JSONObject(resultString);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObjRecv;
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

您还需要库 httpmime 才能使其正常工作。

希望有所帮助:)

关于android - 需要在android中使用HttpPost上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590385/

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