Android请求web的方式
16lz
2021-01-23
1:通过Java.net方式
a)直接通过URL传入参数的Get方式
HttpURLConnection con = (HttpURLConnection)url.openConnection();InputStreamReader in = new InputStreamReader(con.getInputStream());BufferedReader buffer = new BufferedReader(in);while((inputLine=buffer.readLine())!=null){System.out.println(inputLine);strResult += inputLine + "\n";}in.close();con.disconnect();
b)Post方式
con.setDoInput(true);con.setDoOutput(true);con.setRequestMethod("POST");con.setUseCaches(false);con.setInstanceFollowRedirects(false);con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");con.connect();DataOutputStream out = new DataOutputStream(con.getOutputStream());String content = "par=" + URLEncoder.encode("1asdf");out.writeBytes(content);out.flush();out.close();InputStreamReader in = new InputStreamReader(con.getInputStream());BufferedReader buffer = new BufferedReader(in);while((inputLine=buffer.readLine())!=null){System.out.println(inputLine);strResult += inputLine + "\n";}buffer.close();in.close();con.disconnect();
2:Apache
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";//HttpPost连接对象HttpPost httpRequest = new HttpPost(httpUrl);//使用NameValuePair来保存要传递的Post参数List<NameValuePair> params = new ArrayList<NameValuePair>();//添加要传递的参数params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));try{//设置字符集HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");//请求httpRequesthttpRequest.setEntity(httpentity);//取得默认的HttpClientHttpClient httpclient = new DefaultHttpClient();//取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);//HttpStatus.SC_OK表示连接成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setText(strResult);}else{mTextView.setText("请求错误!");}}
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";//HttpGet连接对象HttpGet httpRequest = new HttpGet(httpUrl);try{//取得HttpClient对象HttpClient httpclient = new DefaultHttpClient();//请求HttpClient,取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);//请求成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setText(strResult);}else{mTextView.setText("请求错误!");}}
3:通过Android.ent方式
更多相关文章
- android创建Popwindow弹出菜单的两种方式
- Android 学习笔记3(Activity之间参数传递)
- Android创建子线程和回调主线程的几种方式
- Android 将一个数据对象保存到本地以及读取的方法
- android activity Intent 传值 传对象
- Android 判断屏幕开关状态方式总结
- Android处理XML的三种方式
- Android获取屏幕状态的方式
- Android 唤起app的多种方式