[Java]隨記--HttpClient傳送put請求
阿新 • • 發佈:2019-02-06
@RequestMapping(value="/Xxxxx/authenticate")
public @ResponseBody String getToken(@RequestParam String username, @RequestParam String password) throws Exception {
InputStream is = null;
BufferedReader br = null;
StringBuilder sBuilder = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("url");
httpPut.addHeader("username",username);
httpPut.addHeader("password",password);
HttpResponse httpResponse = httpClient.execute(httpPut);
//連線成功
if(200 == httpResponse.getStatusLine().getStatusCode()){
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
br = new BufferedReader(new InputStreamReader(is));
String tempStr;
sBuilder = new StringBuilder();
while ((tempStr = br.readLine()) != null) {
sBuilder.append(tempStr);
}
br.close();
is .close();
}
}catch (Exception e){
System.out.println(e);
e.printStackTrace();
}
return sBuilder==null? "":sBuilder.toString();
}