自己简单封装的自己项目需要的http请求
生活随笔
收集整理的這篇文章主要介紹了
自己简单封装的自己项目需要的http请求
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
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 : 發(fā)送Post請(qǐng)求到服務(wù)器* Param : params請(qǐng)求體內(nèi)容,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); //設(shè)置連接超時(shí)時(shí)間httpURLConnection.setDoInput(true); //打開(kāi)輸入流,以便從服務(wù)器獲取數(shù)據(jù)httpURLConnection.setDoOutput(true); //打開(kāi)輸出流,以便向服務(wù)器提交數(shù)據(jù)httpURLConnection.setRequestMethod("POST"); //設(shè)置以Post方式提交數(shù)據(jù)httpURLConnection.setUseCaches(false); //使用Post方式不能使用緩存httpURLConnection.setInstanceFollowRedirects(true);//設(shè)置請(qǐng)求體的類型是文本類型httpURLConnection.setRequestProperty("Content-Type", "application/json");httpURLConnection.connect();httpURLConnection.setConnectTimeout(10000);DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());dataOutputStream.write(params.getBytes());dataOutputStream.flush();//獲得輸出流,向服務(wù)器寫(xiě)入數(shù)據(jù)OutputStream outputStream = httpURLConnection.getOutputStream();outputStream.write(data);int response = httpURLConnection.getResponseCode(); //獲得服務(wù)器的響應(yīng)碼if(response == HttpURLConnection.HTTP_OK) {InputStream inptStream = httpURLConnection.getInputStream();System.out.println("=================返回?cái)?shù)據(jù)======================");String resutStr = dealResponseResult(inptStream);String decresultStr = DesEncryptUtil.decrypt(resutStr);return decresultStr;//處理服務(wù)器的響應(yīng)結(jié)果}} catch (IOException e) {e.printStackTrace();}return "";}/** Function : 封裝請(qǐng)求體信息* Param : params請(qǐng)求體內(nèi)容,encode編碼格式*/public static StringBuffer getRequestData(Map<String, String> params, String encode) {StringBuffer stringBuffer = new StringBuffer(); //存儲(chǔ)封裝好的請(qǐng)求體信息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); //刪除最后的一個(gè)"&"} catch (Exception e) {e.printStackTrace();}return stringBuffer;}/** Function : 處理服務(wù)器的響應(yīng)結(jié)果(將輸入流轉(zhuǎn)化成字符串)* Param : inputStream服務(wù)器的響應(yīng)輸入流*/public static String dealResponseResult(InputStream inputStream) {String resultData = null; //存儲(chǔ)處理結(jié)果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;}}在項(xiàng)目里如何使用:
// 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);這樣就可以直接獲取數(shù)據(jù)了。對(duì)resultData數(shù)據(jù)如何處理如下:
可以使用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,"網(wǎng)絡(luò)鏈接錯(cuò)誤,請(qǐng)重試",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保存數(shù)據(jù)*/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);/*** 登錄數(shù)據(jù)存儲(chǔ)完畢,進(jìn)行界面跳轉(zhuǎn)*/Intent it = new Intent(MainActivity.this,MainBusinessActivity.class);startActivity(it);finish();}else {Toast.makeText(MainActivity.this,"賬號(hào)或密碼錯(cuò)誤,請(qǐng)重試",Toast.LENGTH_SHORT).show();}Log.i("ssssss","請(qǐng)求結(jié)果:" + resultJson.toString());}};?
轉(zhuǎn)載于:https://my.oschina.net/u/1399599/blog/853411
總結(jié)
以上是生活随笔為你收集整理的自己简单封装的自己项目需要的http请求的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: iphone开机白苹果_摔过的iPhon
- 下一篇: apk转换ipa在线转换工具_PDF 格