我正在做的应该是一个简单的http帖子,其中包含一个json字符串作为http正文。
?
除响应本身外,所有看起来都很好 - 当我把它变成一个字符串时,它看起来很奇怪(不是文本)。我怎么用纯文本来得到这个?或者在帖子中我做错了什么来得到这个回复? (注意 - 如果我在POST期间排除了cookie,我会从服务器上获得普通的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();
}
}
答案 0 :(得分:0)
您尝试使用平台编码读取UTF-8字符串。 找出返回响应的内容编码,并使用它转换为字符串。
如果您想用2行代码替换上面的代码,请告诉我。我为你准备了一个项目,它已经处理了cookie并转换了内容。