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请求至服务器接口的更多相关文章

  1. Java发送http get/post请求,调用接口/方法

    由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong    转自:http://blog.csdn.net/capmiachael/a ...

  2. 【Android】使用Gson和Post请求和服务器通信

    一.需求文档如下: URL:http://108.188.129.56:8080/example/cal 请求格式: {"para1":10,"para2":2 ...

  3. Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件(二)

    Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件第二版 上次粗略的写了相同功能的代码,这次整理修复了之前的一些BUG,结构也大量修改 ...

  4. Android笔记---使用HttpClient发送POST和GET请求

    在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...

  5. wemall doraemon中Android app商城系统向指定URL发送GET方法的请求代码

    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...

  6. SSH服务器与Android通信(3)--Android客户端发送数据

    Android客户端向SSH服务器发送数据主要有三种情况:通过客户端删除数据.添加数据和修改数据. 1.删除数据 先看看jsp文件里面是怎样删除数据的: <td align="cent ...

  7. Android 9.0/P http 网络请求的问题

    Google表示,为保证用户数据和设备的安全,针对下一代 Android 系统(Android P) 的应用程序,将要求默认使用加密连接,这意味着 Android P 将禁止 App 使用所有未加密的 ...

  8. [转]利用URLConnection来发送POST和GET请求

    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...

  9. 使用httpclient发送get或post请求

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

随机推荐

  1. Elasticsearch5.x创建索引(Java)

    索引创建代码使用官方给的示例代码,我把它在java项目里实现了一遍. 官方示例 1.创建索引 /** * Java创建Index */ public void CreateIndex() { int ...

  2. Cocos Creator 键盘监听事件

    键盘事件键盘.设备重力传感器此类全局事件是通过函数 cc.systemEvent.on(type, callback, target) 注册的.cc.SystemEvent.EventType.KEY ...

  3. unity3d 第一人称脚本解释MouseLook

    using UnityEngine; using System.Collections; /// MouseLook rotates the transform based on the mouse ...

  4. UVAL 4728 Squares(旋转卡壳)

    Squares [题目链接]Squares [题目类型]旋转卡壳 &题解: 听着算法名字,感觉挺难,仔细一看之后,发现其实很简单,就是依靠所构成三角行面积来快速的找对踵点,就可以省去很多的复杂 ...

  5. EL语言表达式 (一)【语法和特点】

    一.基本语法规则: EL表达式语言以“${”开头,以"}"结尾的程序段,具体格式如下: ${expression} 其中expression:表示要指定输出的内容和字符串以及EL运 ...

  6. OpenGL and Vulkan resources

    OpenGL https://www.zhihu.com/question/22005157https://open.gl/https://github.com/cybercser/OpenGL_3_ ...

  7. mysqladmin -u root password

    ERROR : Error appeared during Puppet run: 192.77.108.242_mysql.ppError: mysqladmin -u root  password ...

  8. html5-article元素

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  9. XMLHttpRequest对象(Ajax)的状态码(readystate) HTTP状态代码(status)

    2018-11-28 14:19:00 来自 :XMLHttpRequest对象(Ajax)的状态码(readystate)  HTTP状态代码(status) XMLHttpRequest对象(Aj ...

  10. [protocol]GO enrichment analysis

    [protocol]GO enrichment analysis     背景: 什么是富集分析,自己可以百度.我到目前也没发现一个比较通俗易懂的介绍.直接理解为一种统计学方法就可以了. 用于查看显著 ...