android之 NetTool

package com.itrackstar.tcube.common;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


import android.util.Log;


public class NetTool {
public NetTool() {
super();
}


/**
* 以get方式请求服务器,并且得到返回
*/
public String getJsonStringGet(String uri) throws Exception{
String result=null;
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000);//设置连接超时
Log.i("msg", conn.getResponseCode()+"???????");
if (conn.getResponseCode() == 200){
Log.i("msg", "成功");
InputStream is = conn.getInputStream();//得到网络返回的输入流
result = readData(is, "UTF-8");
}else{
Log.i("msg", "失败");
result="";
}
conn.disconnect();
return result;

}
/**
* post
* @param urlStr
* @param params
* @return
* @throws Exception
*/
  public String getJsonStringPost(String urlStr, List<NameValuePair> params)
    throws Exception {
    String result = null;
    HttpPost httpRequest = new HttpPost(urlStr);
    httpRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params,
    HTTP.UTF_8));
    HttpResponse httpResponse = new DefaultHttpClient()
    .execute(httpRequest);
    Log.i("msg", httpResponse.getStatusLine().getStatusCode()+"");
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
    result = EntityUtils.toString(httpResponse.getEntity());
    } else {
    result = "5";
    }
    return result;
    }
private String readData(InputStream inSream, String charsetName) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}

 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值