public void getWithParams(View view) {
Map<String, String> params = new HashMap<>();
params.put("keyword", "key");
params.put("page", "123");
params.put("order", "0");
startRequest(params, "GET", "/get/param");
}
private void startRequest(final Map<String, String> params, final String method, final String api) {
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
if (params != null && params.size() > 0) {
sb.append("?");
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
sb.append(next.getKey());
sb.append("=");
sb.append(next.getValue());
if (iterator.hasNext()) {
sb.append("&");
}
}
Log.e(TAG, "run: " + sb.toString());
}
String params = sb.toString();
URL url;
if (params != null && params.length() > 0) {
url = new URL(BASE_URL + api + params);
} else {
url = new URL(BASE_URL + api);
}
Log.e(TAG, "run: " + url.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(10000);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.connect();
int responseCode = connection.getResponseCode();
Log.e(TAG, "run: " + responseCode);
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
String line = br.readLine();
Log.e(TAG, "run: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
网友评论