首页 > 代码库 > java HttpURLConnection 接口调用

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 接口调用