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;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM