GET
public static String get(final String url) {
final StringBuilder sb = new StringBuilder();
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
BufferedReader br = null;
InputStreamReader isr = null;
URLConnection conn;
try {
URL geturl = new URL(url);
conn = geturl.openConnection();
conn.connect();
isr = new InputStreamReader(conn.getInputStream());
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
} }}
return sb.toString();
}
});
new Thread(task).start();
String s = null;
try {
s = task.get();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
POST
public static String post(final String url, final Map<String, String> map) {
final StringBuilder sb = new StringBuilder();
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
DataOutputStream out = null;
BufferedReader br = null;
URLConnection conn;
URL posturl = new URL(url);
try {
conn = posturl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
out = new DataOutputStream(conn
.getOutputStream());
StringBuilder request = new StringBuilder();
for (String key : map.keySet()) {
request.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&");
}
out.writeBytes(request.toString());
out.flush();
out.close();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
if (out != null) {
out.close();
} }
return sb.toString(); }
});
String s = null;
new Thread(task).start();
try {
s = task.get();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
发送请求
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("hid","CC:1B:E0:B0:23:DE");
stringStringHashMap.put("bid","CC:1B:E0:B0:23:DE");
stringStringHashMap.put("question",message);
stringStringHashMap.put("token","a39813cf8a550312f24196e7d99c2bc8");
String post = post("http://nim.prec-robot.com/api/speechrcognition/speechrcognition", stringStringHashMap);
System.out.println(post);