android http连接服务器端,Android通过HttpURLConnection连接服务器并进行数据传输-博客...

demo包含GET及POST数据传输方法,将数据以键值对的形式存储到JSONobject里面,与服务器进行数据交互。

1.申请网络权限,在AndroidManifest.xml加入

2.编写服务器连接与交互代码

public class MainActivity extends AppCompatActivity {

//界面控件

Button btnTest;

TextView tvTest;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btnTest=(Button)findViewById(R.id.btn);

tvTest=(TextView)findViewById(R.id.txt);

btnTest.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

//在新线程中进行网络操作

new Thread(){

@Override

public void run() {

try {

//选择请求方式

HttpURLConnectUtils http=new HttpURLConnectUtils();

String rlt=http.DoHttpPOST("输入网址");

//输出返回的结果

System.out.println(rlt);

} catch (MalformedURLException e1) {

e1.printStackTrace();

} catch (IOException e2) {

e2.printStackTrace();

}

}

}.start();

}

});

}

//利用HttpURLConnection联系Http服务器

public class HttpURLConnectUtils {

private HttpURLConnectUtils() {

}

//post

public String DoHttpPost(String mUrl) throws IOException {

URL url = new URL(mUrl);

//初始化创建HttpURLConnection实例

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

//设置当前连接的参数

httpURLConnection.setConnectTimeout(5000); //推荐设置网络延时,如果不设置此项,获取响应状态码时可能引起阻塞

httpURLConnection.setDoOutput(true); //可写

httpURLConnection.setDoInput(true); //可读

httpURLConnection.setUseCaches(false); //不用缓存

//设置HttpURLConnection请求头里面的属性

//设定传送的内容类型是可序列化的java对象

//(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)

//请求头里的属性需要自己根据服务器具体情况设定,下面两个可以不使用(因为这是我目前项目要求的头文件格式)

httpURLConnection.setRequestProperty("Content-type", "application/json");

httpURLConnection.setRequestProperty("accept", "application/json");

//设置请求的方法

httpURLConnection.setRequestMethod("POST");//Post请求

//创建输出流,此时会隐含的进行connect

OutputStream outputStream = httpURLConnection.getOutputStream();

//创建字符流对象并用高效缓冲流包装它,便获得最高的效率,发送的是字符串推荐用字符流,其它数据就用字节流

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));

//输入所需信息

String params = new String();

JSONObject json = new JSONObject();

try {

json.put("Account", "System");

json.put("Password", "123456");

params = json.toString();

}catch (Exception e){

}

//把json字符串写入缓冲区中

bw.write(params);

//提交参数

bw.flush();

outputStream.close();

bw.close();

//获取响应的状态码,判断是否请求成功

int rltCode = httpURLConnection.getResponseCode();

//获取响应状态码的描述, 正常返回"OK"

String msg = httpURLConnection.getResponseMessage();

if (rltCode != 200) //判断响应状态是否成功

{

System.out.println();

return "Error Code--" + rltCode + ", Error Message--" + msg;

}

//接收返回值

//创建文件流对象, InputStream-->InputStreamReader-->BufferedReader

InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

//获取响应数据

StringBuilder builder = new StringBuilder();

//循环读取所有数据

for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {

builder.append(s+"\n");

}

return builder.toString();

}

//get

public String DoHttpGet(String mUrl) throws IOException {

URL url = new URL(mUrl);

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时

httpURLConnection.setReadTimeout(5000);//设置从主机读取数据超时(单位:毫秒)

httpURLConnection.setRequestMethod("GET");

//设置请求头属性

httpURLConnection.setRequestProperty("accept", "application/json");

httpURLConnection.connect(); //此处必须显式进行连接

//以下同Post

//获取响应的状态码,判断是否请求成功

int rltCode = httpURLConnection.getResponseCode();

String msg = httpURLConnection.getResponseMessage(); //获取响应状态码的描述, "OK"

if (rltCode != 200) //判断响应状态是否成功

{

System.out.println();

return "Error Code--" + rltCode + ", Error Message--" + msg;

}

//获取响应内容--读输入流

InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

StringBuilder builder = new StringBuilder();

for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {

builder.append(s);

}

return builder.toString();

}

}

}

3.补充一下,上述为用json传输数据,所以用字符串。但如果是图片之类的数据,需要用字节流,直接调用函数将图像之类的数据转化成Byte数据流,然后bw.write("比特流数据")即可。

本帖子中包含资源

您需要 登录 才可以下载,没有帐号?立即注册

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值