【发布时间】:2026-02-15 09:10:01
【问题描述】:
我正在尝试在我的 Android 应用程序中从 Apache HTTP 迁移到 HttpUrlConnection。我被卡住了,我试着到处寻找,但我无法通过它。这是我正在尝试的。
下面是我的 HTTP 代码:
HttpParams timeoutParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(timeoutParams, 60000);
HttpConnectionParams.setSoTimeout(timeoutParams, 60000);
DefaultHttpClient httpClient = null;
httpClient = new DefaultHttpClient(timeoutParams);
Cookie podCookie = getPodCookie();
if (podCookie != null) {
httpClient.getCookieStore().addCookie(podCookie);
}
HttpPost postMethod = null;
postMethod.addHeader("Authorization", "<auth-header>");
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : parameters.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String queryString = URLEncodedUtils.format(nvps, HTTP.UTF_8);
String modUrl = url + "?" + queryString;
postMethod = new HttpPost(modUrl);
StringEntity entity = new StringEntity(<String JSON to send>, HTTP.UTF_8);
postMethod.setEntity(entity);
postMethod.setHeader("Content-type", "application/json");
HttpResponse reply = httpClient.execute(postMethod);
这是上面代码的 HttpUrlConnection 等价物:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Entry<String, String> entry: parameters.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String queryString = URLEncodedUtils.format(nvps, HTTP.UTF_8);
String modUrl = baseUrl + "?" + queryString;
HttpURLConnection urlConnection = null;
try {
URL url1 = new URL(modUrl);
urlConnection = (HttpURLConnection) url1.openConnection();
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.getCookieStore().add(new URI(url), podCookie);
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(60000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization", <auth-header>);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(<String JSON to send>);
writer.flush()
writer.close();
os.close();
InputStream is = new BufferedInputStream(urlConnection.getInputStream());
String responseString = WebService.convertInputStreamToString(is);
当我尝试上述方法时,我得到一个401 Unauthorized error。我用的是Charles,标题是一样的。
当我尝试在 BufferedWriter 而不是 URL 中添加查询参数时,我将 url 更改为基本 url,如下所示:
URL url1 = new URL(baseUrl);
并将以下行添加到 writer,如下所示:
writer.write(modUrl)
当我这样做时,我得到一个500 Internal Server Error。
在这两种情况下,我都会在InputStream 行上得到一个IOException,即FileNotFoundException。
关于如何解决这个问题的任何想法?
【问题讨论】:
标签: android http httpurlconnection