java HttpURLConnection 接口调用
Posted 坏笑的眼镜男
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java HttpURLConnection 接口调用相关的知识,希望对你有一定的参考价值。
/**
* @param method 传输方式 为get或者post
* @param urlString 基本url
* @param parameters 参数map
* @return
* @throws IOException
*/
public String getToken(String method,String urlString,Map<String, String> parameters) throws IOException{
HttpURLConnection urlConnection = null;
StringBuffer temp = null;
if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(parameters.get(key));
i++;
}
urlString += param;
}
//建立连接
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
//设置参数
//设置连接方式
urlConnection.setRequestMethod(method);;
//需要输出
urlConnection.setDoOutput(true);
//需要输入
urlConnection.setDoInput(true);
//不允许缓存
urlConnection.setUseCaches(false);
//设置请求属性
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Charset", "UTF-8");
urlConnection.setConnectTimeout(40000);
urlConnection.setReadTimeout(40000);
urlConnection.connect();
if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
for (String key : parameters.keySet()) {
param.append("&");
param.append(key).append("=").append(parameters.get(key));
}
String json=JSON.toJSONString(parameters);
urlConnection.getOutputStream().write(json.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
}
//获得响应
int resultCode=urlConnection.getResponseCode();
if(HttpURLConnection.HTTP_OK==resultCode){
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
}
if(temp != null){
return temp.toString();
}else{
return null;
}
}
以上是关于java HttpURLConnection 接口调用的主要内容,如果未能解决你的问题,请参考以下文章
转Java模拟http请求,调用外部api接口:HttpURLConnection和HttpClient的区别
HttpURLConnection 当作请求调用接口不带返回参数的工具类