一个okhttp3 添加header信息,post提交,随机生成数,md5自用b/s基础框架方案

[cc lang=”php”]
package com.huangyifei.android.androidexample;

import android.util.Log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
* Created by Administrator on 2017/1/16.
*/

public class HttpUtils {

OkHttpClient client = new OkHttpClient();

public static final MediaType JSON = MediaType.parse(“application/json; charset=utf-8”);

public String login(String url, String username, String password) throws IOException {
//
//get Randomnum
String myPass = Randomnum();
String myXauth = stringToMD5(“j2jdj1ajovo1qaz” + myPass);
Log.d(“md5”, “md5: ” + myPass);
Log.d(“md5”, “md5: ” + myXauth);
RequestBody body = new FormBody.Builder()
.add(“username”,username)
.add(“password”,password)
.build();
//RequestBody formBody = new FormEncodingBuilder()

Request request = new Request.Builder()
.url(url)
.addHeader(“Pass”,myPass)
.addHeader(“Xauth”,myXauth)
.post(body)
.build();

Response response = client.newCall(request).execute();

String result = response.body().string();

return result;
}

private String Randomnum(){
String strRand=”” ;
for(int i=0;i<15;i++){ strRand += String.valueOf((int)(Math.random() * 10)) ; } return strRand; } /** * 将字符串转成MD5值 * * @param string * @return */ private static String stringToMD5(String string) { byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } } [/cc]

发表评论

电子邮件地址不会被公开。 必填项已用*标注