android网络请求
从活动内发送网络请求,代码如下:
package com.example.shuilangyizu; import android.app.ActionBar; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.device.ScanManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Vibrator; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView;import com.example.shuilangyizu.util.UrlRequestUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 主活动 */ public class MainActivity extends AppCompatActivity { private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action private ActionBar actionBar; private Vibrator mVibrator; private Animation buttonPress; String projectPath = ""; //获取所有数据请求路径 private String systemUrl = "";//创建Handler对象mHandler,mHandler是Handler类型的成员变量 public Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { Object obj = msg.obj; int what = msg.what; if (what==1){ } if (what==2){ } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); actionBar = getActionBar(); if (actionBar!=null){ actionBar.show(); } Thread thread = new Thread(){ @Override public void run(){ //调用发送请求方法 Map<String,Object> paramMap = new HashMap<>(); paramMap.put("what","1"); projectPath = getString(R.string.projectPath); stockupSystemUrl = getString(R.string.systemUrl); UrlRequestUtil.sendPostRequest(mHandler, projectPath+systemUrl,paramMap); } }; thread.start(); } }
网络请求工具类代码如下:
特别注意这两行代码:
//dStream.writeBytes(paramString);//中文会乱码
//dStream.write(paramString.getBytes());//中文不会乱码
package com.example.shuilangyizu.util; import android.os.Handler; import android.os.Message; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; /** * 网络请求工具类 */ public class UrlRequestUtil { /** * 发送post请求 * * @param mHandler : * @param url:请求发送地址 * @param paramMap:请求发送的参数 * 无论哪里调用必须存入一个消息标记what数字类型,用于区分消息提醒的位置。 * what取值范围如下定义(有新的消息提醒位置后续定义): */ public static void sendPostRequest(Handler mHandler,String url, Map<String,Object> paramMap){ BufferedReader br = null; HttpURLConnection conn= null; try{ int what = paramMap.get("what")==null?0:Integer.parseInt(paramMap.get("what").toString()); URL reqURL = new URL(url); conn=(HttpURLConnection) reqURL.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String paramFormat =""; for (String key : paramMap.keySet()) { String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString(); if (paramFormat!=""){ paramFormat = paramFormat + "&" + key + "=" + value; }else{ paramFormat = key + "=" + value; } } String paramString= String.format(paramFormat); //设置参数 DataOutputStream dStream = new DataOutputStream(conn.getOutputStream()); //dStream.writeBytes(paramString);//中文会乱码 dStream.write(paramString.getBytes());//中文不会乱码 dStream.close(); //打开网络通信输入流 InputStream is = conn.getInputStream(); //通过is创建InputStreamReader对象 InputStreamReader isr = new InputStreamReader(is, "UTF-8"); //通过isr创建BufferedReader对象 br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while((line = br.readLine())!= null){ sb.append(line); } //创建消息 Message msg = new Message(); //消息标记 msg.what = what; //设置消息内容 msg.obj = sb.toString(); //发送消息到主线程 mHandler.sendMessage(msg); }catch(Exception e){ e.printStackTrace(); }finally { if (conn != null) { conn.disconnect(); } if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }