HTTP POST 网络请求
代码
// 增加一个线程,来访问服务器
new Thread() {
@Override
public void run() {
try {
URL httpUrl = new URL(goods_url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//与服务器建立连接;
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("content-type", "application/json charset=UTF-8");
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");//设置请求方式为GET
//发送Post强求,开启其读写的功能
// conn.setDoOutput(true);
conn.setDoInput(true);
String strJson = "{\"authToken\":\"afly_shop\"}";//拼接需要发送的内容;以字节的方式写入到输出流中;
OutputStream is = conn.getOutputStream();
byte[] content = strJson.getBytes("UTF-8");
is.write(content);
is.flush();
final StringBuffer sb = new StringBuffer();//把获取的数据不断存放到StringBuffer中;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));//使用reader向输入流中读取数据,并不断存放到StringBuffer中;
String line;
while ((line = reader.readLine()) != null) {//只要还没有读取完,就不断读取;
sb.append(line);//在StringBuffer中添加;
}
result = sb.toString();
//handler向主线程发送数据
Message msg=new Message();
msg.getData().putString("result", result);
msg.what=0;
handler.sendMessage(msg);
// handler.post(new Runnable() {//使用Handler更新UI;当然这里也可以使用sendMessage();handMessage()来进行操作;
// @Override
// public void run() {
// Good good = new Good();
// good = GetGood.getGood(sb.toString());
// // tv.setText(good.getGoodName());//StringBuffer转化为String输出;
// GoodsName[0] = good.getGoodName();
// show.setText(GoodsName[0]);
// }
// });
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//handler接收子线程数据
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==0)
{
jsonresult = msg.getData().getString("result");
}
};