java http请求方式
方式一:
URL restServiceURL = new URL(URL+URl);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.addRequestProperty("Content-type","application/json");
// httpConnection.addRequestProperty("Date", Date);
// httpConnection.addRequestProperty("X-Auth", sign);
// httpConnection.addRequestProperty("Content-Md5", content_Md5);
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400 )
{ InputStream is = httpConnection.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null)
{ sbf.append(temp); sbf.append("\r\n"); }
restResponse = sbf.toString();
}
else{
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
inputStream = httpConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((restResponse = reader.readLine()) != null) {
resultBuffer.append(restResponse);
}
}
方式二:
HttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(testUrl);
request.setHeader("Content-type", "application/json");
request.setHeader("Date", Date);
request.setHeader("X-Auth", sign);
request.setHeader("Content-Md5", content_Md5);
HttpResponse response = client.execute(request);
if (response.getCode()==200){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
}
else {}