我也是才刚开始微信开发,很差的地方你们多批评。java
说到微信开发不得不说的一个地方就是网络链接发送请求,得到返回数据。这个是全部平台开发的基础。我这里用的是HttpURLConnection 来发送请求url地址。 具体以下:缓存
请求分为 两类请求:服务器
一、get请求微信
get请求比较简单,无需设置过多网络
public static String doGet(String strUrl) throws IOException{ String result = ""; URL url = new URL(strUrl); HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); // 设定请求的方法为"GET",默认是GET httpUrlConnection.setRequestMethod("GET"); // 链接 httpUrlConnection.connect(); // 调用HttpURLConnection链接对象的getInputStream()函数, // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 InputStream inStrm = httpUrlConnection.getInputStream(); // <===注意,实际发送请求的代码段就在这里 // 输入流使用Reader读取 BufferedReader reader = new BufferedReader(new InputStreamReader(inStrm)); String lines; while ((lines = reader.readLine()) != null) { result += lines +"\n"; } reader.close(); // 断开链接 httpUrlConnection.disconnect(); return result;//最后 获得请求返回结果result }二、post请求
稍微须要多设置下参数,其余跟get请求相似
微信开发
public static String doPost(String strUrl,String content) throws IOException{ String result = ""; URL url = new URL(strUrl); HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); // 设置是否向httpUrlConnection输出,由于这个是post请求,参数要放在 // http正文内,所以须要设为true, 默认状况下是false; httpUrlConnection.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认状况下是true; httpUrlConnection.setDoInput(true); // Post 请求不能使用缓存 httpUrlConnection.setUseCaches(false); // 设定传送的内容类型是可序列化的java对象 // (若是不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // 设定请求的方法为"POST",默认是GET httpUrlConnection.setRequestMethod("POST"); // 链接,从上述第2条中url.openConnection()至此的配置必需要在connect以前完成, httpUrlConnection.connect(); // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, // 因此在开发中不调用上述的connect()也能够)。 OutputStream outStrm = httpUrlConnection.getOutputStream(); // 如今经过输出流对象构建对象输出流对象,以实现输出可序列化的对象。 ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm); // 向对象输出流写出数据,这些数据将存到内存缓冲区中 objOutputStrm.writeObject(content); // 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream) objOutputStrm.flush(); // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中, // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 objOutputStrm.close(); // 调用HttpURLConnection链接对象的getInputStream()函数, // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 InputStream inStrm = httpUrlConnection.getInputStream(); // <===注意,实际发送请求的代码段就在这里 // 输入流使用Reader读取 BufferedReader reader = new BufferedReader(new InputStreamReader(inStrm)); String lines; while ((lines = reader.readLine()) != null) { result += lines +"\n"; } reader.close(); // 断开链接 httpUrlConnection.disconnect(); return result; }
以上是写的两个方法封装httpUrlConnection处理方法。代码解释的很清楚,文字就没有多说。不懂能够留言评论。app
刚刚开始博客,你们捧场。
ide