public static String test(String paramter){
try{
URL url = new URL("http://127.0.0.1:8056/api?paramter="+paramter);
//調用URL對象的openConnection( )來獲取HttpURLConnection對象實例
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//請求方法爲POST
conn.setRequestMethod("POST");
//設置鏈接超時爲5秒
conn.setConnectTimeout(5000);
//容許輸入輸出
conn.setDoInput(true);
conn.setDoOutput(true);
//不能緩存
conn.setUseCaches(false);
//設置頭部信息
conn.setRequestProperty("headerdata", "ceshiyongde");
//設置 Content-Type
conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
//服務器返回東西了,先對響應碼判斷
String result = null;
if (conn.getResponseCode() == 200) {
//用getInputStream()方法得到服務器返回的輸入流
InputStream in = conn.getInputStream();
//流轉換爲二進制數組,read()是轉換方法
byte[] data = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = in.read(data)) != -1){
bos.write(data,0,len);
}
bos.close();
result= new String(bos.toByteArray(), "UTF-8");
in.close();
}
return result;
}catch (Exception e){
e.printStackTrace();
return null;
}
}