2019独角兽企业重金招聘Python工程师标准>>>
package www.tydic.com.util;import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;/****/
public class HttpUtils {/** Function : 发送Post请求到服务器* Param : params请求体内容,encode编码格式*/public static String submitPostData(String strUrlPath,String params, String encode) {byte[] data = params.getBytes();try {URL url = new URL(strUrlPath);HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();httpURLConnection.setConnectTimeout(3000); //设置连接超时时间httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存httpURLConnection.setInstanceFollowRedirects(true);//设置请求体的类型是文本类型httpURLConnection.setRequestProperty("Content-Type", "application/json");httpURLConnection.connect();httpURLConnection.setConnectTimeout(10000);DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());dataOutputStream.write(params.getBytes());dataOutputStream.flush();//获得输出流,向服务器写入数据OutputStream outputStream = httpURLConnection.getOutputStream();outputStream.write(data);int response = httpURLConnection.getResponseCode(); //获得服务器的响应码if(response == HttpURLConnection.HTTP_OK) {InputStream inptStream = httpURLConnection.getInputStream();System.out.println("=================返回数据======================");String resutStr = dealResponseResult(inptStream);String decresultStr = DesEncryptUtil.decrypt(resutStr);return decresultStr;//处理服务器的响应结果}} catch (IOException e) {e.printStackTrace();}return "";}/** Function : 封装请求体信息* Param : params请求体内容,encode编码格式*/public static StringBuffer getRequestData(Map<String, String> params, String encode) {StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息try {for(Map.Entry<String, String> entry : params.entrySet()) {stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");}stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"} catch (Exception e) {e.printStackTrace();}return stringBuffer;}/** Function : 处理服务器的响应结果(将输入流转化成字符串)* Param : inputStream服务器的响应输入流*/public static String dealResponseResult(InputStream inputStream) {String resultData = null; //存储处理结果ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;try {while((len = inputStream.read(data)) != -1) {byteArrayOutputStream.write(data, 0, len);}} catch (IOException e) {e.printStackTrace();}resultData = new String(byteArrayOutputStream.toByteArray());return resultData;}}
在项目里如何使用:
// TODO: http request.String account = loginAccount.getText().toString().trim();String password = loginPassword.getText().toString().trim();Map<String, String> paramsMap = new HashMap<String, String>();paramsMap.put("login_nbr", account);paramsMap.put("login_type", Constant.LOGIN_TYPE);paramsMap.put("pwd", password);Gson gson = new Gson();String all = gson.toJson(paramsMap);all = DesEncryptUtil.encrypt(all);String resultData = HttpUtils.submitPostData(Constant.APP_PAHT_LOGIN, all, "UTF-8");if (resultData==""){resultData="";}Message msg = new Message();Bundle datas = new Bundle();datas.putString("value", resultData);datas.putString("account", account);datas.putString("password", password);msg.setData(datas);handler.sendMessage(msg);
这样就可以直接获取数据了。对resultData数据如何处理如下:
可以使用Gson处理,我使用的Java的JSONObject处理工具
方法如下:
Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);Bundle data = msg.getData();String val = data.getString("value");String account = data.getString("account");String password = data.getString("password");if ("".equals(val)||val.equals(null)){Toast.makeText(MainActivity.this,"网络链接错误,请重试",Toast.LENGTH_SHORT).show();return;}JSONObject resultJson = JSONObject.fromObject(val);String resultCode = resultJson.get("CODE").toString();if (resultCode.equals(Constant.RESULT_CODE)){String CUST_NAME = resultJson.get("CUST_NAME").toString();String RESULT = resultJson.get("RESULT").toString();String CUST_ID = resultJson.get("CUST_ID").toString();String ORG_CODE = resultJson.get("ORG_CODE").toString();String ORG_ID = resultJson.get("ORG_ID").toString();/*** SharedPreferences保存数据*/SharedPreferencesUtils.put(MainActivity.this,"account",account);SharedPreferencesUtils.put(MainActivity.this,"password",password);SharedPreferencesUtils.put(MainActivity.this,"CUST_NAME",CUST_NAME);SharedPreferencesUtils.put(MainActivity.this,"RESULT",RESULT);SharedPreferencesUtils.put(MainActivity.this,"CUST_ID",CUST_ID);SharedPreferencesUtils.put(MainActivity.this,"ORG_CODE",ORG_CODE);SharedPreferencesUtils.put(MainActivity.this,"ORG_ID",ORG_ID);/*** 登录数据存储完毕,进行界面跳转*/Intent it = new Intent(MainActivity.this,MainBusinessActivity.class);startActivity(it);finish();}else {Toast.makeText(MainActivity.this,"账号或密码错误,请重试",Toast.LENGTH_SHORT).show();}Log.i("ssssss","请求结果:" + resultJson.toString());}};