android之发送Get或Post请求至服务器接口
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log; @SuppressLint("NewApi")
public class ServiceUtil {
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
public static String getServiceInfo (String strUrl,String ip,String port)
{
System.setProperty("https.proxyHost", ip);
System.setProperty("https.proxyPort", port);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(90000);
conn.setReadTimeout(90000);
conn.setInstanceFollowRedirects(false);
conn.connect(); InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
Log.e("ServiceUtil-->>getServiceInfo",e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e("ServiceUtil-->>getServiceInfo",e.getMessage());
}
}
if (conn != null) {
conn.disconnect();
}
}
if(null!=rs){
rs = rs.replace( "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "")
.replace("<string xmlns=\"http://tempuri.org/\">", "")
.replace("</string>", "").replace("\r", "")
.replace("\n", "")
.replace("<string xmlns=\"http://tempuri.org/\" />", "");
}
LogUtil.WriteLog(rs);
return rs;
} /**
* post请求获取数据
* @param strUrl 请求地址,如: "http://....asmx/HelloWork"
* @param params 设置发送的参数,如:"key=1&name=1";//设置发送的参数
* @return
*/
public static String getServiceInfoPost(String strUrl,String params)
{
String strResult="";
try{ byte[] entity = params.getBytes();
HttpURLConnection con = (HttpURLConnection) new URL(strUrl).openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setConnectTimeout(90000);
con.setReadTimeout(90000);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",String.valueOf(entity.length));
con.getOutputStream().write(entity);
int code =con.getResponseCode();//响应代码 200表示成功
if(code==200){
InputStream inStream = con.getInputStream();
strResult=new String(readInputStream(inStream), "UTF-8");
if(null!=strResult){
strResult = strResult.replace( "<boolean xmlns=\"http://tempuri.org/\">", "")
.replace("</boolean>", "")
.replace("</string>", "").replace("\r", "")
.replace("\n", "")
.replace("<string xmlns=\"http://tempuri.org/\" />", "");
}
}
}
catch(Exception ex){
Log.e("getServiceInfoPost",ex.getMessage());
}
return strResult;
} /**
* 从输入流中读取数据
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) {
try{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10000];
int len = 0;
while( (len = inStream.read(buffer)) !=-1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();//网页的二进制数据
outStream.close();
inStream.close();
return data;
}
catch(Exception ex){
return null;
}
}
}
android之发送Get或Post请求至服务器接口的更多相关文章
- Java发送http get/post请求,调用接口/方法
由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong 转自:http://blog.csdn.net/capmiachael/a ...
- 【Android】使用Gson和Post请求和服务器通信
一.需求文档如下: URL:http://108.188.129.56:8080/example/cal 请求格式: {"para1":10,"para2":2 ...
- Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件(二)
Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件第二版 上次粗略的写了相同功能的代码,这次整理修复了之前的一些BUG,结构也大量修改 ...
- Android笔记---使用HttpClient发送POST和GET请求
在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...
- wemall doraemon中Android app商城系统向指定URL发送GET方法的请求代码
URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...
- SSH服务器与Android通信(3)--Android客户端发送数据
Android客户端向SSH服务器发送数据主要有三种情况:通过客户端删除数据.添加数据和修改数据. 1.删除数据 先看看jsp文件里面是怎样删除数据的: <td align="cent ...
- Android 9.0/P http 网络请求的问题
Google表示,为保证用户数据和设备的安全,针对下一代 Android 系统(Android P) 的应用程序,将要求默认使用加密连接,这意味着 Android P 将禁止 App 使用所有未加密的 ...
- [转]利用URLConnection来发送POST和GET请求
URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...
- 使用httpclient发送get或post请求
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
随机推荐
- win10升级后,无法ping通vmware的centos解决方法
win10是lenovo thinkpad460上面的,是正版的.无法做设置,不让其自动升级.10月8日节后第一天上班,电脑要求更新,我就点更新. 结果就发现无法ping通vmware中的centos ...
- Dart async proc
//dart import 'dart:io';import 'dart:async'; Future printDailyNewsDigest1() { print('A:'); File file ...
- Git操作说明
Git操作说明 1.将本地项目上传到GitHub 1) 首先在GitHub上注册帐户 2) 在GitHub上创建仓库 3) Pc安装Git客户端(Git Bach) 4) 打开 ...
- Selenium基本使用(十二)测试报告生成
报告目录结构 Reporter根目录 | |-------------LOGS | | | ...
- bootstrap ui
附加访问地址:http://www.bootcss.com/p/jquery-ui-bootstrap/
- 在lnmp1.3布置的web服务器上运行thinkphp3.2.3项目pathinfo路径模式
通过我的经历希望能给大家带来一些帮助: 我是在Linux系统上通过https://lnmp.org/install.html设置Nginx服务器,使用的是lnmp1.3版本,之后将一个thinkphp ...
- ubuntu安装rvm
sudo apt-get install curl git-core bash -s stable < <(curl -s https://raw.github.com/wayneeseg ...
- 把本地windows系统上的mysql数据库移到linux系统服务器上,mysql数据库拒绝访问
Mysql连接报错 原因是:远程服务器不允许你的其他程序访问它的数据库.所以,我们要对远程服务器进行设置,使它允许你进行连接. 步骤:一.进入mysql客户端,输入:use mysql; 二.输入:s ...
- mac下编译cpu only caffe并用xCode建caffe工程
mac编译caffe 好像又变容易了,直接git clone下载blvc源码,make.config里去掉了CPU_ONLY前面的注释,并没有安装任何依赖,也可能是自己mac上本来有, xCode里调 ...
- pyspider 示例二 升级完整版绕过懒加载,直接读取图片
pyspider 示例二 升级完整版绕过懒加载,直接读取图片,见[升级写法处] #!/usr/bin/env python # -*- encoding: utf-8 -*- # Created on ...