我使用HttpURLConnection POST来获取响应。我能够得到响应码200,但responseString的编码如下:: RPB%+ C // 17Wr uvQJr-N9
这是我使用::
的代码public static String getPOSTAJAX(String getURL,String impersonationID,String getPOSTParameters)
{
// get Impersonation ID
String getimpersonationID = "bearer "+impersonationID;
String getResponseline = "";
String getPOSTResponse = null;
String postCookies = "sid="+impersonationID;
try
{
//Open HttpURLConnection
URL url = new URL(getURL);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//add request header
if (impersonationID != null && impersonationID != " ") {
urlConn.setRequestProperty("Authorization", getimpersonationID);
urlConn.setRequestProperty("Accept-Encoding","gzip, deflate");
urlConn.setRequestProperty("Cookie", postCookies);
}
urlConn.setRequestProperty("Accept","application/json,text/plain,*/*");
urlConn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlConn.setRequestProperty("Connection", "keep-alive");
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36");
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Length", String.valueOf(getPOSTParameters.getBytes().length));
urlConn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//send the POSt Request
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
DataOutputStream writeRequest = new DataOutputStream(urlConn.getOutputStream());
writeRequest.writeBytes(getPOSTParameters);
writeRequest.flush();
writeRequest.close();
//To get the Response Codes
int responseCode = urlConn.getResponseCode();
logger.debug("\nSending 'POST' request to URL::" +url);
logger.debug("Post parameters ::"+getPOSTParameters);
logger.debug("Response Code ::" + responseCode);
//parse the response
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), Charset.forName("UTF-8")));
while((getResponseline = reader.readLine()) != null)
{
builder.append(getResponseline);
builder.append("\n");
}
reader.close();
getPOSTResponse = builder.toString();
//logger.debug("\n "+getPOSTResponse);
//Disconnect the connection
urlConn.disconnect();
}
catch (IOException ioe) {
logger.error("\n"+ioe);
}
return getPOSTResponse;
}
有人可以建议如何解码响应吗?
答案 0 :(得分:0)
我建议使用InflaterInputStream类,而不是使用InputStreamReader
,可用于解压缩数据。
StringBuilder builder = new StringBuilder();
InflaterInputStream in = new InflaterInputStream(urlConn.getInputStream()), new Inflater(true));
int i;
while((i=in.read())!=-1){
builder.append(i);
}
getPOSTResponse = builder.toString();
答案 1 :(得分:0)
我也有同样的问题,我删除了除Content-Type
以外的所有请求属性,现在它正在运行。
Donno现在如何/为何如此有效。