在Java中,如何使用 application / x-www-form-urlencoded 和 Authorization Basic 发送请求。我总是得到响应服务器返回的HTTP响应代码:URL为400 Postman Headers image
我尝试了以下代码:
try{
url=new URL("https://secure.URL target");
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("cache-control", "no-cache");
conn.setRequestProperty("Authorization", "Basic" + authEncode);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data=URLEncoder.encode("username","UTF-8")
+"="+ URLEncoder.encode(user, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") +"="
+ URLEncoder.encode(pass, "UTF-8");
data += "&" + URLEncoder.encode("grant_type", "UTF-8") +"="
+ URLEncoder.encode(grant,"UTF-8");
conn.connect();
OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
is=conn.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
result=br.readLine();
System.out.println(result);
}catch(IOException e){
e.printStackTrace();
}finally{
if(conn != null){
conn.disconnect();
}
}
}