android 发送http请求

实践是知识的母亲,知识是生活的明灯。这篇文章主要讲述android 发送http请求相关的知识,希望能为你提供帮助。
好久没写博客了,由于公司要做android,笔者也是第一次接触。
【android 发送http请求】这是在项目中遇到一个比較麻烦的问题。记录下来备忘(本人刚接触。有不正确的地方请不吝赐教)。


发送请求的代码:

package com.jiujian.mperdiem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class AppUtil {// 本地測试路径 public static final String webBaseUrl = " http://ip:端口" ; /* * 訪问URL。获取结果 method: GET, POST */ public static String loadUrlResponse(String method, String urlString) { HttpURLConnection conn = null; // 连接对象 InputStream is = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(urlString); // URL对象 conn = (HttpURLConnection) url.openConnection(); // 使用URL打开一个链接 conn.setDoInput(true); // 同意输入流,即同意下载 conn.setDoOutput(true); // 同意输出流,即同意上传 conn.setUseCaches(false); // 不使用缓冲 conn.setRequestMethod(method); // 使用get请求 is = conn.getInputStream(); // 获取输入流。此时才真正建立链接 InputStreamReader isr = new InputStreamReader(is); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = " " ; while ((inputLine = bufferReader.readLine()) != null) { result.append(inputLine).append(" \n" ); }} catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } }return result.toString(); } }




调用代码:

StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl); sbUpdateDeviceRefreshInstall.append(" XXX?
UserId=" ); sbUpdateDeviceRefreshInstall.append(getUserId()); AppUtil.loadUrlResponse(" POST" , sbUpdateDeviceRefreshInstall.toString());




代码是没有问题的,但是app端发送请求。server端却一直没有信息打印。错误信息是:android.os.NetworkOnMainThreadException
最后才发现android 3.0以后就不同意在主线程上进行网络訪问的,
于是把代码改成:

new Thread(){ @Override public void run() { StringBuffer sbUpdateDeviceRefreshInstall = new StringBuffer(AppUtil.webBaseUrl); sbUpdateDeviceRefreshInstall.append(" XXX?UserId=" < span style=" font-family: ' Microsoft YaHei' ; " > ); < /span> sbUpdateDeviceRefreshInstall.append(getUserId()); AppUtil.loadUrlResponse(" POST" , sbUpdateDeviceRefreshInstall.toString()); } }.start();


这样就没问题了。


假设是刚接触android,能够推荐看:第一行代码,这本书对于入门来说挺不错的。

个人主页:http://www.itit123.cn/  很多其它干货等你来拿













    推荐阅读