【发布时间】:2014-07-23 09:48:56
【问题描述】:
我正在做一个项目,该项目需要我发送一个帖子请求到 http://sagecell.sagemath.org/kernel(只是一个帖子,没有数据)以及两个额外的标题, Accept-Encoding:identity 和accepted_tos:true。
如果像这样使用默认的 httpClient,这可以正常工作:
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
String url = UrlUtils.getKernelURL();
httpPost.setURI(URI.create(url));
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(HEADER_ACCEPT_ENCODING,VALUE_IDENTITY));
postParameters.add(new BasicNameValuePair(HEADER_TOS,"true"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
webSocketResponse = gson.fromJson(new InputStreamReader(inputStream), WebSocketResponse.class);
inputStream.close();
但是,如果我想通过 OkHttpClient 使用相同的东西,它会给我一个 403 错误:
httpClient = new OkHttpClient();
public static final MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonMediaType, "");
Request request = new Request.Builder()
.addHeader(HEADER_ACCEPT_ENCODING, VALUE_IDENTITY)
.addHeader(HEADER_TOS, "true")
.url(url)
.post(body) //I've tried null here as well
.build();
Response response = httpClient.newCall(request).execute();
Log.i(TAG,"STATUS CODE"+response.code()); //This is 403
Ion 甚至 HttpUrlConnection 等库也是如此,但似乎只有 Apache 客户端可以工作。
任何关于为什么这不起作用的答案将不胜感激。
【问题讨论】:
-
你把你的整个logcat贴出来了吗
-
不会崩溃,应该是2xx的状态码是403。
标签: android httpclient okhttp