HttpURLConnection URL带参数的网络请求
程序员文章站
2022-03-23 23:16:39
...
点击按钮发起网络请求
btn_getUrlParams.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String,String> params = new HashMap<>();
params.put("keyword","搜索");//参数,方便后面进行拼接
params.put("page","50");
params.put("order","1");
startRequest(params,"GET","/get/param"); //发起请求的方法
Log.d(TAG, "map result--->"+params.toString());
}
});
/**
* @param params 参数
* @param method get/post
* @param api 接口
*/
private void startRequest(final Map<String, String> params, final String method, final String api) {
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader bufferedReader=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.d(TAG, "sb result--->"+sb.toString()); //拼接
}
URL url;
if (params !=null && params.size()>0) {
url = new URL(BASE_URL+api+sb.toString()); //BASE_URL 服务器IP+接口+加拼接的参数组成 带参数的URL
}else{
url = new URL(BASE_URL+api);
}
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(method); //请求方法
httpURLConnection.setConnectTimeout(10000); //设置连接超时
httpURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");//请求体
httpURLConnection.setRequestProperty("Accept ","*/*");
httpURLConnection.connect();
//如果连接成功就读取服务器返回的数据
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG, "result--->"+bufferedReader.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
推荐阅读
-
java解析出url请求的路径和参数键值对类(解析出url请求的路径,包括页面)
-
php获取URL中带#号等特殊符号参数的解决方法
-
JS获取url参数,JS发送json格式的POST请求方法
-
基于url的get请求springmvc出现中文参数乱码
-
django views重定向到带参数的url
-
js处理url中的请求参数(编码/解码)
-
android用okhttp发送带header的post请求(参数为键值对格式)
-
JS获取url中的请求参数,以及整合thymeleaf获取model中的属性值
-
分享一款一直在维护的【网络开发运维|通用调试工具】: http请求, websocket,cmd, RSA,DES, 参数签名工具,脚本批量生成工具,google动态口令,端口检测,组件注册,js混淆...
-
后端代码发送请求调用带MultipartFile参数的接口