下面是使用Java 7
编译和执行的代码段,其结果与Java 8
的结果不同。
在进入Native之前尝试使用apache httpclient
。我假设与其他库的问题是相同的
输出Jdk7
{"error":"invalid_grant","error_description":"authentication failure"}
java.io.IOException: Server returned HTTP response code: 400 for URL: XXX
at ``sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
输出Jdk8:预期结果
public String requestSFAuthToken(Map<String, String> sfAttributes) throws Exception{
StringBuilder result = new StringBuilder();
String request = sfAttributes.get("url");
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
OutputStreamWriter writer = null;
BufferedReader reader = null;
try{
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "application/json");
conn.setDoOutput(true);
conn.setAllowUserInteraction(true);
conn.connect();
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getParameters(sfAttributes));
writer.flush();
String line;
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
result.append(line);
}
writer.close();
reader.close();
conn.disconnect();
}catch(Exception e){
if(conn != null){
String error ;
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((error = reader.readLine()) != null) {
System.out.println(error);
}
}
throw e;
}finally{
if(conn != null){
conn.disconnect();
}
if(writer != null){
writer.close();
}
if(reader != null){
reader.close();
}
}
return result.toString();
}
private String getParameters(Map<String, String> sfAttributes) throws UnsupportedEncodingException {
String params = URLEncoder.encode("grant_type", "UTF8")
+ "="+ URLEncoder.encode(sfAttributes.get("grant_type"), "UTF8");
params += "&"+ URLEncoder.encode("client_id","UTF8")
+ "="+ URLEncoder.encode(sfAttributes.get("client_id"), "UTF8");
params += "&"+ URLEncoder.encode("client_secret", "UTF8")
+ "="+ URLEncoder.encode(sfAttributes.get("client_secret"), "UTF8");
params += "&"+ URLEncoder.encode("username", "UTF8")
+ "="+ URLEncoder.encode(sfAttributes.get("username"), "UTF8");
params += "&"+ URLEncoder.encode("password", "UTF8")
+ "="+ URLEncoder.encode(sfAttributes.get("password"), "UTF8");
return params;
}