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 协议最新的版本和建 ...
随机推荐
- CentOS6.5 安装Spark集群
一.安装依赖软件Scala(所有节点) 1.下载Scala:http://www.scala-lang.org/files/archive/scala-2.10.4.tgz 2.解压: [root@H ...
- python math random
很有用个的工具 值得好好看看,这是作者(python发明者)对于工作中使用到的大多数场景的提炼 //test.py 1 import math 2 3 print abs(-10) 4 print m ...
- Faster-rcnn实现目标检测
Faster-rcnn实现目标检测 前言:本文浅谈目标检测的概念,发展过程以及RCNN系列的发展.为了实现基于Faster-RCNN算法的目标检测,初步了解了RCNN和Fast-RCNN实现目标检 ...
- css抖动动画
button{ animation: beat 6s ease 0s infinite normal; } @keyframes beat { 0% { transform: translateY(0 ...
- 1.display:flex布局笔记
/*display:flex布局方式主要运用于垂直居中的效果*/ 一.Flex译为Flexible Box(弹性盒子),任何一个容器都可以指定为Flex布局 注:设置为Flex布局之后,子元素的flo ...
- python对缩进的严格要求
一般的编辑器都会默认Tab键为四格缩进,但是在python脚本中,Tab与直接4个tablespace空格是有区别的. 一般表现为报错信息如下: IndentationError: unindent ...
- 在liunx系统里面进行复制文件的时候报错:cp:omitting directiory
在复制的时候执行命令:cp /TEST/test1 /TEST/test2 结果报错:cp:omitting directior 报错原因:test1下面还有文件,不能删除 解决办法:cp -r / ...
- STL之Deque容器
1.Deque容器 1)deque是“double-ended queue”的缩写,和vector一样都是STL的容器,deque是双端数组,而vector是单端的. 2)deque在接口上和vect ...
- sitecore系统教程之使用修补程序文件自定义Sitecore配置
您可以使用修补程序文件在Sitecore中添加或更改配置设置.Sitecore将修补程序文件与Sitecore.config 文件合并,以创建在运行时使用的配置文件. 本主题描述: 补丁文件放置 补丁 ...
- Eclipse中tomcat更改部署路径 deply path
默认是部署在项目元数据文件夹.metadata文件夹下,需要更改到tomcat/webapps目录下 Eclipse中tomcat service设置 选择window ----show view-- ...