我在做什麼應該是一個簡單的http帖子,其中包含一個json字符串作爲http正文。使用JSON在http POST後發生奇怪的響應
?
所有看起來不錯,除了響應本身 - 當我把它變成一個字符串它回來看起來很奇怪(不是文本)。我怎樣才能以純文本得到這個?或者我在帖子中做錯了什麼,以獲得此回覆? (注 - 如果我在POST過程中排除的cookies我從服務器獲取純HTML回瓦特/有效的「拒絕訪問」消息)
的完整代碼此解決方案是低於
public class BaseHttpService {
public ResponseAndCookies doHttpPostWithUrlWithJson(String url, String key, CookieStore cookies) {
try {
StringEntity se = new StringEntity("{\"filters\":true}");
se.setContentType("text/xml");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpPost httpost = new HttpPost(url);
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-Type", "application/json");
return executeHttpRequest(httpost, cookies);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public ResponseAndCookies executeHttpRequest(HttpRequestBase http, CookieStore cookieStore) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String result = "";
if (cookieStore != null) {
((DefaultHttpClient) httpclient).setCookieStore(cookieStore);
}
try {
response = httpclient.execute(http);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<Cookie> cookies = ((DefaultHttpClient) httpclient).getCookieStore().getCookies();
CookieStore postCookieStore = ((DefaultHttpClient) httpclient).getCookieStore();
ResponseAndCookies x = new ResponseAndCookies();
x.setCookies(cookies);
x.setResponse(result);
x.setCookieStore(postCookieStore);
httpclient.getConnectionManager().shutdown();
return x;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
這主要是一種猜測,但如果您爲[InputStreamReader]設置編碼(http://developer.android.com/reference/java/io/InputStreamReader.html#InputStreamReader%28java.io。 InputStream,%20java.lang.String%29)。我不知道這樣做的確切價值,但我會先給UTF-8一個去。 – harism 2011-05-14 18:14:04
顯式帶有UTF-8似乎沒有改變結果 – 2011-05-14 19:02:18