android org.apache.http.httpresponse,上传图片了就会报org.apache.http.client.HttpResponseException: Not Foun...

建议弃用httpclient,使用HttpURLConnection:

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class HttpConnector {

public static final int TIMEOUT_MS = 10 * 1000;

public static String performRequest(String url, File file, Map additionalHeaders) {

String response = null;

try {

HashMap map = new HashMap();

if (additionalHeaders != null)

map.putAll(additionalHeaders);

URL parsedUrl = new URL(url);

HttpURLConnection connection = openConnection(parsedUrl, file);

for (String headerName : map.keySet()) {

connection.addRequestProperty(headerName, map.get(headerName));

}

int responseCode = connection.getResponseCode();

if (responseCode == -1) {

// -1 is returned by getResponseCode() if the response code could not be retrieved.

// Signal to the caller that something was wrong with the connection.

throw new IOException("Could not retrieve response code from HttpUrlConnection.");

}

String charset = "utf-8";

String contentEncoding = null;

String contentType = null;

for (Map.Entry> header : connection.getHeaderFields().entrySet()) {

if (header.getKey() != null) {

List headerValueList = header.getValue();

if (headerValueList != null && headerValueList.size() > 0) {

StringBuffer headerValueSB = new StringBuffer();

for (int i = 0; i < headerValueList.size(); i++) {

headerValueSB.append(headerValueList.get(i));

if (i != headerValueList.size() - 1) {

headerValueSB.append(";");

}

}

if (header.getKey().equals("Content-Type")) {

contentType = headerValueSB.toString();

} else if (header.getKey().equals("Content-Encoding")) {

contentEncoding = headerValueSB.toString();

}

}

}

}

charset = parseCharset(contentType, contentEncoding, charset);

if (responseCode == 200) {

//成功

response = entityFromConnection(connection, charset);

}

} catch (Exception e) {

// e.printStackTrace();

}

return response;

}

/**

* Create an {@link HttpURLConnection} for the specified {@code url}.

*/

protected static HttpURLConnection createConnection(URL url) throws IOException {

return (HttpURLConnection) url.openConnection();

}

/**

* Opens an {@link HttpURLConnection} with parameters.

*

* @param url

* @return an open connection

* @throws IOException

*/

private static HttpURLConnection openConnection(URL url, File file) throws IOException {

HttpURLConnection connection = createConnection(url);

connection.setConnectTimeout(TIMEOUT_MS);

connection.setReadTimeout(TIMEOUT_MS);

connection.setUseCaches(false);

connection.setDoInput(true);

connection.setRequestMethod("POST");

addBodyIfExists(connection, file);

return connection;

}

private static String parseCharset(String contentType, String contentEncoding,

String defaultCharset) {

if (contentType != null) {

String[] params = contentType.split(";");

for (int i = 1; i < params.length; i++) {

String[] pair = params[i].trim().split("=");

if (pair.length == 2) {

if (pair[0].equals("charset")) {

return pair[1];

}

}

}

}

if (contentEncoding != null && !contentEncoding.equals("")) {

return contentEncoding;

}

return defaultCharset;

}

private static String entityFromConnection(HttpURLConnection connection, String charset) throws IOException {

String data = null;

InputStream inputStream;

try {

inputStream = connection.getInputStream();

} catch (IOException ioe) {

inputStream = null;

}

if (inputStream != null) {

data = readData(inputStream, charset);

}

return data;

}

private static String readData(InputStream inSream, String charsetName) throws IOException {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = -1;

while ((len = inSream.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

byte[] data = outStream.toByteArray();

outStream.close();

inSream.close();

return new String(data, charsetName);

}

private static void addBodyIfExists(HttpURLConnection connection, File file) {

try {

if (file != null) {

connection.setDoOutput(true);

connection.addRequestProperty("Content-Type", "application/octet-stream; charset=utf-8");

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

FileInputStream fStream = new FileInputStream(file);

/* 设定每次写入1024bytes */

try {

int bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

int length = -1;

/* 从文件读取数据到缓冲区 */

while ((length = fStream.read(buffer)) != -1) {

/* 将数据写入DataOutputStream中 */

out.write(buffer, 0, length);

}

} finally {

fStream.close();

out.flush();

out.close();

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

调用:String response = HttpConnector.performRequest(uploadUrl, file, null);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用org.apache.http.client.HttpClient文件的Java示例: ```java import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class FileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file.jpg"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File(filePath)); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); try { httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println(responseString); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在此示例中,我们使用HttpClient创建一个HttpPost请求对象,并使用MultipartEntityBuilder创建一个multipart/form-data实体,以便我们可以将文件作为二进制数据添加到请求中。最后,我们使用execute方法将请求发送到服务器,并从响应中提取响应字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值