将一段 HttpClient 写的代码,改用OkHttp3来实现 40C

以下是HttpClient的代码,功能就是向一个url发送get请求,并携带一个.p12格式的证书文件

 package com.sinnk.web.module.weixin.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

public class Test {

    public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
        // TODO Auto-generated method stub
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("C:\\apiclient_cert.p12"));
        try {
            keyStore.load(instream, "1499761822".toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, "1499761822".toCharArray())
                .build();
        // Allow TLSv1 protocol only
        @SuppressWarnings("deprecation")
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }

                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

    }

}

要求用OkHttp3来实现。

1个回答

public class PersistentCookieStore {

private static final String LOG_TAG = "PersistentCookieStore";

private static final String COOKIE_PREFS = "Cookies_Prefs";

private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;  
private final SharedPreferences cookiePrefs;  


public PersistentCookieStore(Context context) {  
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);  
    cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();  

    //将持久化的cookies缓存到内存中 即map cookies  
    Map<String, ?> prefsMap = cookiePrefs.getAll();  
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {  
        String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");  
        for (String name : cookieNames) {  
            String encodedCookie = cookiePrefs.getString(name, null);  
            if (encodedCookie != null) {  
                Cookie decodedCookie = decodeCookie(encodedCookie);  
                if (decodedCookie != null) {  
                    if (!cookies.containsKey(entry.getKey())) {  
                        cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());  
                    }  
                    cookies.get(entry.getKey()).put(name, decodedCookie);  
                }  
            }  
        }  
    }  
}  

protected String getCookieToken(Cookie cookie) {  
    return cookie.name() + "@" + cookie.domain();  
}  

public void add(HttpUrl url, Cookie cookie) {  
    String name = getCookieToken(cookie);  

    //将cookies缓存到内存中 如果缓存过期 就重置此cookie  
    if (!cookie.persistent()) {  
        if (!cookies.containsKey(url.host())) {  
            cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());  
        }  
        cookies.get(url.host()).put(name, cookie);  
    } else {  
        if (cookies.containsKey(url.host())) {  
            cookies.get(url.host()).remove(name);  
        }  
    }  

    //讲cookies持久化到本地  
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
    prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));  
    prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));  
    prefsWriter.apply();  
}  

public List<Cookie> get(HttpUrl url) {  
    ArrayList<Cookie> ret = new ArrayList<Cookie>();  
    if (cookies.containsKey(url.host()))  
        ret.addAll(cookies.get(url.host()).values());  
    return ret;  
}  

public boolean removeAll() {  
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
    prefsWriter.clear();  
    prefsWriter.apply();  
    cookies.clear();  
    return true;  
}  

public boolean remove(HttpUrl url, Cookie cookie) {  
    String name = getCookieToken(cookie);  

    if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {  
        cookies.get(url.host()).remove(name);  

        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
        if (cookiePrefs.contains(name)) {  
            prefsWriter.remove(name);  
        }  
        prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));  
        prefsWriter.apply();  

        return true;  
    } else {  
        return false;  
    }  
}  

public List<Cookie> getCookies() {  
    ArrayList<Cookie> ret = new ArrayList<Cookie>();  
    for (String key : cookies.keySet())  
        ret.addAll(cookies.get(key).values());  

    return ret;  
}  

/** 
 * cookies 序列化成 string 
 * 
 * @param cookie 要序列化的cookie 
 * @return 序列化之后的string 
 */  
protected String encodeCookie(SerializableOkHttpCookies cookie) {  
    if (cookie == null)  
        return null;  
    ByteArrayOutputStream os = new ByteArrayOutputStream();  
    try {  
        ObjectOutputStream outputStream = new ObjectOutputStream(os);  
        outputStream.writeObject(cookie);  
    } catch (IOException e) {  
        Log.d(LOG_TAG, "IOException in encodeCookie", e);  
        return null;  
    }  

    return byteArrayToHexString(os.toByteArray());  
}  

/** 
 * 将字符串反序列化成cookies 
 * 
 * @param cookieString cookies string 
 * @return cookie object 
 */  
protected Cookie decodeCookie(String cookieString) {  
    byte[] bytes = hexStringToByteArray(cookieString);  
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);  
    Cookie cookie = null;  
    try {  
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);  
        cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();  
    } catch (IOException e) {  
        Log.d(LOG_TAG, "IOException in decodeCookie", e);  
    } catch (ClassNotFoundException e) {  
        Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);  
    }  

    return cookie;  
}  

/** 
 * 二进制数组转十六进制字符串 
 * 
 * @param bytes byte array to be converted 
 * @return string containing hex values 
 */  
protected String byteArrayToHexString(byte[] bytes) {  
    StringBuilder sb = new StringBuilder(bytes.length * 2);  
    for (byte element : bytes) {  
        int v = element & 0xff;  
        if (v < 16) {  
            sb.append('0');  
        }  
        sb.append(Integer.toHexString(v));  
    }  
    return sb.toString().toUpperCase(Locale.US);  
}  

/** 
 * 十六进制字符串转二进制数组 
 * 
 * @param hexString string of hex-encoded values 
 * @return decoded byte array 
 */  
protected byte[] hexStringToByteArray(String hexString) {  
    int len = hexString.length();  
    byte[] data = new byte[len / 2];  
    for (int i = 0; i < len; i += 2) {  
        data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));  
    }  
    return data;  
}}  

[java] view plain copy
public class SerializableOkHttpCookies implements Serializable {

private transient final Cookie cookies;  
private transient Cookie clientCookies;  

public SerializableOkHttpCookies(Cookie cookies) {  
    this.cookies = cookies;  
}  

public Cookie getCookies() {  
    Cookie bestCookies = cookies;  
    if (clientCookies != null) {  
        bestCookies = clientCookies;  
    }  
    return bestCookies;  
}  

private void writeObject(ObjectOutputStream out) throws IOException {  
    out.writeObject(cookies.name());  
    out.writeObject(cookies.value());  
    out.writeLong(cookies.expiresAt());  
    out.writeObject(cookies.domain());  
    out.writeObject(cookies.path());  
    out.writeBoolean(cookies.secure());  
    out.writeBoolean(cookies.httpOnly());  
    out.writeBoolean(cookies.hostOnly());  
    out.writeBoolean(cookies.persistent());  
}  

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {  
    String name = (String) in.readObject();  
    String value = (String) in.readObject();  
    long expiresAt = in.readLong();  
    String domain = (String) in.readObject();  
    String path = (String) in.readObject();  
    boolean secure = in.readBoolean();  
    boolean httpOnly = in.readBoolean();  
    boolean hostOnly = in.readBoolean();  
    boolean persistent = in.readBoolean();  
    Cookie.Builder builder = new Cookie.Builder();  
    builder = builder.name(name);  
    builder = builder.value(value);  
    builder = builder.expiresAt(expiresAt);  
    builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);  
    builder = builder.path(path);  
    builder = secure ? builder.secure() : builder;  
    builder = httpOnly ? builder.httpOnly() : builder;  
    clientCookies =builder.build();  
}  

}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
求写一段代码
一个表:aboutrn字段:path w h sel(选择类型)rn我的目的:当sel为真的时候,在前台显示这个表:rn<%sql="select top 1 * from about where class=4 order by id desc"rn set rsn=server.CreateObject("adodb.recordset")rn rsn.open sql,conn,1,1rn if rsn("sel")=true then%>rn rn rn " height="<%=rsn("h")%>">rn " />rn rn " quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="<%=rsn("w")%>" height="<%=rsn("h")%>">rn rn rn rn <%end if%>rnrn这是一个显示flash广告代码。当后台设置了宽(w)、高(h)以及sel为真的时候,前台显示flash。rn上面的代码不知道哪里出了问题。就是不显示。
vb.net 代码改用c#写。谢谢
Sub Item_Bound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) _ rnHandles DataGrid1.ItemDataBound rn e.Item.Cells(0).CssClass = "locked" rnEnd Subrnrn以上代码用C#如何写
一段用JavaScript写的实现AJAX代码
这段代码本人已经用了3,4年了并在多个大的项目中使用,应该没什么问题,现在贴出来和大家共享。rnrn使用方法:rn 假设一个网页中存在一个ID为,DIV_AJAX的DIV对象,url 为需要请求的网页rnwait_str 为正在请求时显示的信息可以是HTML,error_str当请求什么的网页失败时间显示的详细rnfunction ajax("DIV_AJAX","http://qq.fxsou.com","正在读取数据请稍等...","抱歉数据请求失败!")rnfunction ajax(obj,url,wait_str,error_str) //ajax方法来发送数据;;;obj,DOM对象的ID,URL,请求的页面,wait_str,等待时显示的字符串rn rn var http_req;rn if (window.XMLHttpRequest) rn rn http_req=new XMLHttpRequest();rn //http_req.overrideMimeType('text/xml');rn rn else if (window.ActiveXObject) rn http_req=new ActiveXObject("Microsoft.XMLHTTP");rn rn// document.getElementById(obj).innerHTML=wait_str;rn http_req.onreadystatechange = function()rn if (http_req.readyState == 4) //状态rnrn if (http_req.status == 200) //成功返回rn if(http_req.responseText!=null && http_req.responseText!="")rn rn document.getElementById(obj).innerHTML=http_req.responseText;rn rn elsern rn document.getElementById(obj).style.display="none";rn rn rn else //返回不正常rnrn document.getElementById(obj).innerHTML=error_str;rn rn rn ;rn http_req.open("GET", url, true);rn http_req.send(null);rn rnrn
一段代码大家来看下
下面的代码中 this.Visible = false;中的this有点搞不明白,是引用PageElement类的实例,还是引用Panel类的实例rn望大家指点下rn public class PageElement:System.Web.UI.WebControls.Panelrn rn protected override void OnLoad(EventArgs e)rn rn if (!Page.IsPostBack)rn rn string pageElementPower = Mud.Biz.Utilsrn string[] powers = pageElementPower.Split('|');rn for (int i = 0; i < powers.Length; i++)rn rn if (ElementID == powers[i])rn rn return;rn rn rn this.Visible = false; ////////rn rn rnrn public string ElementIDrn rn getrn rn tryrn rn return this.Attributes["ElementID"].ToString();rn rn catchrn rn return "";rn rn rn rn rn
高手来给我一段代码
我想做的就是UBB标签,一个文本域上有个按钮叫“换行”,点击一下,下面的文本域里面就添加一个“ ”怎么实现?小弟菜鸟哦,最好能给段代码
Android代码-OkHttp3
OkHttp3 基于OkHttp3封装的网络请求库 功能点 支持Http/Https协议/自定义Https证书认证 支持同步/异步请求 支持异步延迟执行 支持Post/Get/Put/Delete请求 支持Cookie持久化,支持Gzip压缩 支持协议头参数Head设置 支持二进制参数、JSON、表单提交、SOAP提交 支持Gson解析、Unicode自动转码、请求参数编码以及服务器响应编码设置 支持四种缓存类型请求:仅网络、仅缓存、先网络再缓存、先缓存再网络 支持自定义缓存存活时间与缓存清理功能 当Activity/Fragment销毁时自动取消相应的所有网络请求,支持取消指定请求 异步请求响应自动切换到UI线程,摒弃runOnUiThread Application中自定义全局配置/增加系统默认配置 支持文件和图片上传/批量上传,支持同步/异步上传,支持进度提示 支持文件下载/批量下载,支持同步/异步下载,支持进度提示 支持文件断点下载,独立下载的模块摒弃了数据库记录断点的过时方法 完整的日志跟踪与异常处理 支持请求结果拦截以及异常处理拦截 支持单例客户端,提高网络请求速率 完整
将一段代码做成dll
麻烦dephi的朋友帮我将下面的代码做成dll,然后发送我的信箱:langzhi888@sina.comrn第一个发的朋友将获得50分,其他的前五位朋友每人将获得10分。谢谢rn因为我用的是VB,所以请详细注明调用方法rnrnhttp://dev.csdn.net/develop/article/26/26046.shtmrnrnrn获取其他进程中ListView的文本 zswangII [原作] rn关键字 ListView Delphi OpenProcess WriteProcessMemory ReadProcessMemory LVM_GETITEM rn出处 rn rn (*//rn标题:获取其他进程中ListView的文本rn说明:Window2000+Delphi6调试通过rn设计:Zswangrn支持:wjhu111@21cn.comrn日期:2004-03-25rn//*)rnrnuses CommCtrl;rnrnfunction ListViewColumnCount(mHandle: THandle): Integer;rnbeginrn Result := Header_GetItemCount(ListView_GetHeader(mHandle));rnend; ListViewColumnCount rnrnfunction GetListViewText(mHandle: THandle; mStrings: TStrings): Boolean;rnvarrn vColumnCount: Integer;rn vItemCount: Integer;rn I, J: Integer;rn vBuffer: array[0..255] of Char;rn vProcessId: DWORD;rn vProcess: THandle;rn vPointer: Pointer;rn vNumberOfBytesRead: Cardinal;rn S: string;rn vItem: TLVItem;rnbeginrn Result := False;rn if not Assigned(mStrings) then Exit;rn vColumnCount := ListViewColumnCount(mHandle);rn if vColumnCount <= 0 then Exit;rn vItemCount := ListView_GetItemCount(mHandle);rn GetWindowThreadProcessId(mHandle, @vProcessId);rn vProcess := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_READ orrn PROCESS_VM_WRITE, False, vProcessId);rn vPointer := VirtualAllocEx(vProcess, nil, 4096, MEM_RESERVE or MEM_COMMIT,rn PAGE_READWRITE);rn mStrings.BeginUpdate;rn tryrn mStrings.Clear;rn for I := 0 to vItemCount - 1 do beginrn S := '';rn for J := 0 to vColumnCount - 1 do beginrn with vItem do beginrn mask := LVIF_TEXT;rn iItem := I;rn iSubItem := J;rn cchTextMax := SizeOf(vBuffer);rn pszText := Pointer(Cardinal(vPointer) + SizeOf(TLVItem));rn end;rn WriteProcessMemory(vProcess, vPointer, @vItem,rn SizeOf(TLVItem), vNumberOfBytesRead);rn SendMessage(mHandle, LVM_GETITEM, I, lparam(vPointer));rn ReadProcessMemory(vProcess, Pointer(Cardinal(vPointer) + SizeOf(TLVItem)),rn @vBuffer[0], SizeOf(vBuffer), vNumberOfBytesRead);rn S := S + #9 + vBuffer;rn end;rn Delete(S, 1, 1);rn mStrings.Add(S);rn end;rn finallyrn VirtualFreeEx(vProcess, vPointer, 0, MEM_RELEASE);rn CloseHandle(vProcess);rn mStrings.EndUpdate;rn end;rn Result := True;rnend; GetListViewText rnrn//Examplernprocedure TForm1.FormCreate(Sender: TObject);rnbeginrn RegisterHotKey(Handle, 1, MOD_WIN, VK_F2);rnend;rnrnprocedure TForm1.FormDestroy(Sender: TObject);rnbeginrn UnRegisterHotKey(Handle, 1);rnend;rnrnprocedure TForm1.WMHOTKEY(var Msg: TWMHOTKEY);rnbeginrn case Msg.HotKey ofrn 1:rn GetListViewText(rn WindowFromPoint(Point(Mouse.CursorPos.X, Mouse.CursorPos.Y)),rn MemoText.Lines);rn end;rnend;
关于Okhttp3 https双向验证实现代码
使用前提: okhttp3 官网:http://square.github.io/okhttp/ 可能不同的情况会出现不同的情况,所以只能说我的代码逻辑不是百分之百可以适应不同环境的app,仅仅提供一个参考 1)首先准备,客户端证书,服务端证书 本代码使用的证书是:client.p12,trust.bks ,并将证书存放到res/raw文件夹下 2)书写代码: pub
OkHttp3的使用,代码奉上
okhttp3.0网上的资料太少啦,今天我来为大家写一篇okhttp3.0的使用 okhttp3.0中引入啦大量的builder 1、创建OkHttpClient的builder private static final okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder(); 2、创建OkHttpClient的实例 设置超时时间 设置cookies缓存
求助帮写一段代码
要求在一个php里实现输入不同的密码读取不同的DIVrn比如输入密码123 显示“下载链接一”rn输入密码1234 显示“下载链接二”
请帮忙写一段代码
十进制转化成八进制的递归和非递归算法
一段写晕掉的代码
// 代码重新格式化于20110717/** * prop.h */#include #define CONCAT_DIRECT(a,b) a##b#define CONCAT(a,b) CONCAT_DIRECT(a,b)#define TOSTR_DIRECT(tag) #tag#define TOSTR(tag) TOSTR
帮忙写一段代码,急!
这是hsv转换到rgb的算法:rns/=255rnif s=0(s是一个从0到1的一个小数)rn r=g=b=v(r,g,b,v是byte型的)rnelsern h/=60;(h是0到360的一个值)rn i=integer(h)rn f=h-irn a=v*(1-s)rn b=v*(1-s*f)rn c=v*(1-s*(1-f))rn swith(i)rn case 0:r=v;g=c;B=a;rn case 1:r=b;g=v;B=a;rn case 2:r=a;g=v;B=c;rn case 3:r=a;g=b;B=v;rn case 4:r=c;g=a;B=v;rn case 5:r=v;g=a;B=b
ajax 我写的一段代码
<!--var xmlHttp = false;try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = fals
谁能帮我写一段代码?
登陆页面:临时卡管理rn然后分学生,老师和部门rn学生里面就是基本信息:班级,卡的类型(正式卡和临时卡),院系,卡号,老师的和学生的一样,rn部门的基本信息是:部门,卡的类型(正式卡和临时卡),卡号,有急用哪位大哥能不能帮忙写一下急用啊,我才学ASP呢什么都不会,谁能不能帮个忙?用ASP写。rn
开会讨论,写一段scala 代码
package com. /** * Created by xxxx on 2/16/2017. */ object Test extends App{ def Nn(): Unit ={ for(x =y)){ val xy = if(x*y < 10) x*y +" " else x*y print( y +" * " +x +" = "+ x
帮忙写一段JS验证代码!
[code=HTML]rn rn rn 图片1:rn rn rn rn 标题1:rn rn rn rn rn rn 图片2:rn rn 标题2:rn rn rn rn 图片3:rn rn 标题3:rn rn rn rn 图片4:rn rn 标题4:rn rn rn rn 图片5:rn rn 标题5:rn rn rn rn 图片6:rn rn 标题6:rn rn rn rn 图片7:rn rn 标题7:rn rn rnrn[/code]rnrn要求文本框img和title不能同明为空rn即img1、title1不能同时为空rn img2、title2不能同时为空rn ……rn我折腾了好长时间,没写出来,谢谢了!
高手请进,写一段代码
需要写一段字符串加密代码rn1.要对0至9数字进行转换rn2.要对a至z 26个小写字母进行转换rn3.要对A至Z 26个大写字母进行转换rn4.其它字符保持原样不变rn5.数字及字母对应表如下:rn原字符 0123456789 a至z A至Zrn对应字符 EAhfk91sQe 8VptI57XNYqM2KnUo03FJWjlrv DLPZZxymHSbdgOG4uRcCwzB6airnrn比如字符串 1a2$8 经过转换后应该是 A8h$Qrnrn请高手帮忙写这样的转换代码rnrn
求写一段简单的代码!!
我段代码的功能是像VB编程环境里的工程与属性界面窗口的左边一样,鼠标移动到那里出来←||→,你进行鼠标拖动能对窗口进行改变,并可以进行改变工程与属性里的窗口宽度!!rn
展示一段我写的代码!
[code=C#] public class Linern rn private ConcurrentQueue intQueue = new ConcurrentQueue(Enumerable.Range(0,10000));rnrn private ConcurrentQueue< Task< double>> calculateQueue = new ConcurrentQueue>();rnrn private ConcurrentQueue> factorialQueue = new ConcurrentQueue>();rnrn private ConcurrentBag resultBag = new ConcurrentBag();rnrn private Task CalculateTask(int i)rn rn TaskCompletionSource tcs = new TaskCompletionSource();rn double d = i;rn tryrn rn tcs.SetResult(Math.Acos(Math.Cosh(Math.Cos(Math.Tan(Math.Tanh(d))))));rn rn catch (Exception ex)rn rn tcs.SetException(ex);rn rn return tcs.Task;rn rnrn private Task Factorial(double de)rn rn Func tempFuc = delegate(double d)rn rn long i = Convert.ToInt64(d);rn long result = 1;rn while (i > 0)rn rn result = i * result;rn i--;rn rn return result;rn ;rn return Task.Factory.FromAsync(tempFuc.BeginInvoke(de, null, null), tempFuc.EndInvoke);rn rnrn private void AddCalculate()rn rn int i;rn while (intQueue.TryDequeue(out i))rn rn calculateQueue.Enqueue(CalculateTask(i));rn rn rnrn private void AddFactorial()rn rn Task task;rn while (calculateQueue.TryDequeue(out task))rn rn double d = task.Result;rn factorialQueue.Enqueue(Factorial(d));rn rn rnrn private void AddQueue()rn rn Task task;rn while (factorialQueue.TryDequeue(out task))rn rn long l = task.Result;rn if (l<500&&l>0)rn rn intQueue.Enqueue(Convert.ToInt32(l));rn rn resultBag.Add(l);rn rn rnrn public void mainFuc()rn rn Parallel.Invoke(() => AddCalculate(); , () => Thread.Sleep(1000); AddFactorial(); , () => Thread.Sleep(3000); AddQueue(); );rn rn rn[/code]
求写txt文件的一段代码
rn各位:rnrn 我要在test.txt 中写入以下数据:rnrn ksrn 1234 14 ,,,, ///rn ......rn *** rn rn 说明:rn ks: 为标示符,表示开始rn 中间的四组数据为主要内容,每组间用空格分开,最后以回车换行rn *** 为标示符,表示数据结束rn rn 问:rn 这种特殊符号怎么写入?每组分开及换行怎么表示?(要求:数据一个个写入,而不是一次写一行!)rn
求一段代码的实现
定义string 然后让用户输入,然后已字符递减的形式输出(如果字符长度相同的话,比较ASCII码输出)rn最后在输出所有连一起的句子rn『不是作业,我就看到C++书了,做完习题了,然后我想自己扩展一下,就碰到问题了啊,以前是用int 定义,递减的时候输入--就行,但是string 我用-- 就报错了,用while接受>> 希望大家帮忙一下啊 感激不尽 感激不尽啊』rnrn我是这样写的rn[code=C/C++]int main()rnrn cout<<"Enter strings\n";rn string st;rn while(cin>>st)rn rn cout<
python写的一段分页的代码
代码: from django.utils.safestring import mark_safe class Paginator(object): def __init__(self,current_page,total_item_count,base_url,per_page_count=10,show_pager_count=11): ...
一段写只读内存的代码
rn相关网站:http://edu.teamsourcing.com.cnrnrn逆向一个驱动程序时发现了一段写只读内存的代码,这个代码实际是Mark Russinovich 很早写的一段代码。如下:rnrnWriteReadOnlyMemory proc near ; CODE XREF: sub_108CC+D4 prn ; sub_10A06+D4 p ...rnrnBaseAddress = dword ptr -4 ; 保存映射的内存地址rnSpinLock = dword ptr 8rnarg_4 = dword ptr 0ChrnLength = dword ptr 10hrnrn mov edi, edirn push ebprn mov ebp, esprn push ecxrn push ebxrn push esirn xor esi, esirn push esirn push esirn push esirn push [ebp+Length]rn push [ebp+SpinLock]rn call ds:IoAllocateMdlrn mov ebx, eaxrn cmp ebx, esirn jnz short loc_105C6rn mov eax, 0C0000001hrn jmp short loc_1063Frn; ---------------------------------------------------------------------------rnrnloc_105C6: ; CODE XREF: WriteReadOnlyMemory+1D jrn push edirn push ebxrn call ds:MmBuildMdlForNonPagedPoolrn push 1rn push esirn push ebxrn call ds:MmProbeAndLockPagesrn push esirn push ebxrn call ds:MmMapLockedPagesrn mov edi, eaxrn cmp edi, esirn mov [ebp+BaseAddress], edirn jnz short loc_105F0rn mov esi, 0C0000001hrn jmp short loc_1062Ern; ---------------------------------------------------------------------------rnrnloc_105F0: ; CODE XREF: WriteReadOnlyMemory+47 jrn lea eax, [ebp+SpinLock]rn push eaxrn call ds:KeInitializeSpinLockrn lea ecx, [ebp+SpinLock]rn call ds:KfAcquireSpinLockrn mov ecx, [ebp+Length]rn mov esi, [ebp+arg_4]rn mov edx, ecxrn shr ecx, 2rn rep movsdrn mov ecx, edxrn and ecx, 3rn rep movsbrn mov dl, alrn lea ecx, [ebp+SpinLock]rn call ds:KfReleaseSpinLockrn push ebxrn push [ebp+BaseAddress]rn call ds:MmUnmapLockedPagesrn xor esi, esirnrnloc_1062E: ; CODE XREF: WriteReadOnlyMemory+4E jrn push ebxrn call ds:MmUnlockPagesrn push ebxrn call ds:IoFreeMdlrn mov eax, esirn pop edirnrnloc_1063F: ; CODE XREF: WriteReadOnlyMemory+24 jrn pop esirn pop ebxrn leavern retn 0ChrnWriteReadOnlyMemory endprnrn下面是Mark Russinovich 很早写的一段代码,目的是写只读内存。rnNTSTATUS WriteReadOnlyMemory (char *dest, char *source, int length) rn rnKSPIN_LOCK tempSpinLock; rnKIRQL oldirql; rnPMDL mdl; rnPVOID writableAddress;rnrnmdl = IoAllocateMdl((PVOID) dest, length, FALSE, FALSE, NULL); rnif (mdl == NULL) rnreturn STATUS_UNSUCCESSFUL; rnMmBuildMdlForNonPagedPool(mdl); rnMmProbeAndLockPages(mdl, KernelMode, IoWriteAccess); rnwritableAddress = MmMapLockedPages(mdl, KernelMode); rnif (writableAddress == NULL) rnMmUnlockPages(mdl); rnIoFreeMdl(mdl); rnreturn STATUS_UNSUCCESSFUL; rnrnrnKeInitializeSpinLock(&tempSpinLock); rnKeAcquireSpinLock(&tempSpinLock, &oldirql); rnRtlCopyMemory(writableAddress, source, length); rnKeReleaseSpinLock(&tempSpinLock, oldirql);rnrnMmUnmapLockedPages(writableAddress, mdl); rnMmUnlockPages(mdl); rnIoFreeMdl(mdl); rnreturn STATUS_SUCCESS; rnrn 相关网站:http://edu.teamsourcing.com.cnrn
帮我写一段简单的代码
在一个表格里,如果未登陆显示登陆框,登陆后变为用户信息rn登陆框和用户信息不用提供rn另问:在一个表格加了rnrn不知道是加的太多了,还是怎么了,页面执行速度很慢,换成普通代码就好了,rn可是我还是想分开管理,怎么办
帮忙写一段代码,很简单
代码一:rnrn如果是第一次浏览本站,COOKIE里写一个值0,浏览第二页的时候写,以此类推,多浏览一页,数字就增加一次.COOKIE的时间期限是两天,以第一次浏览的时候开始计算时间.rnrn代码二:rn读取代码一中所写入COOKIE的浏览次数,以及从第一次浏览到现在的时间.
求大神写一段代码
小弟略懂php对js一窍不通rn比如说一个字符串 2017020711rn是10位 那么就把前后分开 补个0在日期和数字中间 也就是 20170207011rn这种 咋写 大神支招
我写的一段代码(莫名其妙)
存储过程:rnCreate PROCEDURE dbo.selectinteractivetxtrn @size intrnASrnbeginrndeclare @sqlstr nvarchar(300)rnset @sqlstr='select top'+str(@size)+' id,WebName,WebDomain,txtCount FROM WeberInteractive WHERE (Status = 1) ORDER BY txtCount%100' rn exec(@sqlstr)rn endrn RETURNrnrnCreate PROCEDURE dbo.updateinteractivetxtcountrn @id bigintrnASrnupdate WeberInterActive set txtCount=txtCount+1 where id=@idrn RETURNrnrnrnrnpublic StringBuilder GetTxt()rn rn string StyleType;rn StringBuilder builder = new StringBuilder();rn SqlCommand mySqlCommand = new SqlCommand();rn mySqlCommand.CommandType = CommandType.StoredProcedure;rn mySqlCommand.CommandText = "selectinteractivetxt";rn mySqlCommand.Connection = mySqlConnection;rnrn mySqlCommand.Parameters.Add(new SqlParameter("@size", SqlDbType.Int)); //add parameter @sizern mySqlCommand.Parameters["@size"].Value = 1; //数量rnrn SqlCommand mySqlCommand1 = new SqlCommand();rn mySqlCommand1.CommandType = CommandType.StoredProcedure;rn mySqlCommand1.CommandText = "updateinteractivetxtcount";rn mySqlCommand1.Connection = mySqlConnection;rnrn SqlDataAdapter MydataAdapter = new SqlDataAdapter();rn MydataAdapter.SelectCommand = mySqlCommand;rn MydataAdapter.UpdateCommand =mySqlCommand1;rn rn SqlParameter id = MydataAdapter.UpdateCommand.Parameters.Add("@id",SqlDbType.BigInt);rn id.SourceColumn = "id";rn id.SourceVersion = DataRowVersion.Original;rnrn DataSet ds = new DataSet();rn OpenSql(mySqlConnection);rn MydataAdapter.Fill(ds,"table1");rn CloseSql(mySqlConnection);rn builder.Append("");rn foreach (DataRow dr in ds.Tables["table1"].Rows)rn rn builder.Append("" + dr["WebName"].ToString() + dr["txtCount"] + " ");rn dr["txtCount"]=10;rn rn MydataAdapter.Update(ds, "table1");rn builder.Append("");rn return builder;rn
httpclient代码
该文件是httpclient的源代码,java类型的
多线程 wait-notify 写一段代码来解决生产者-消费者问题
生产者-消费者 该模式在现实生活中很常见,在项目开发中也广泛应用,它是线程间通信的经典应用。 生产者是一堆线程,消费者是另一堆线程,内存缓冲区可以使用 List集合存储数据。该模式的关键之处是如何处理多线程之间的协调通信,内存缓冲区为空的时候,消费者...
帮忙写一段重载+号来连接字符串的代码!!感激不尽!
各位哥哥姐姐,小弟是C++初学者,学习中遇到一点小问题,就是不会用重载+号来连接字符串,请你们为你写一段代码让我参考一下!!在此小弟感激不尽!
写一段客户端代码,来隐藏控件---------------在线等
rn rn rn rn rnrnrn我想在写一段客户端代码,来隐藏控件 TextBox1 imgrn求大家帮助..
如何用javascript写一段代码来查看html页面的源文件
如何用javascript写一段代码来查看html页面的源文件
写一段代码将Hello World转换成dlroW olleH。
答案: String str = "Hello World"; //首先定义一个Hello World字符串 StringBuilder sb = new StringBuilder(str); //创建一个StringBuilder变量,将定义的字符串传递进去 System.out.println(sb.reverse().toString()); //使用StringBuilder
求高手将一段JS代码转换成以Java来实现
请高手将以下Javascript改成Java实现。如能实现50分相赠。不够另加分。rnrn//-----------rnfunction Generate_Brief(text,length)rn if(text.length < length) return text;rn var Foremost = text.substr(0,length);rn rn var re = /<(\/?)(BODY|STYLE|SCRIPT|P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|TABLE|TR|TD|TH|INPUT|SELECT|TEXTAREA|OBJECT|A|UL|OL|LI|BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT|SPAN)[^>]*(>?)/ig;rn rn var Singlable = /BASE|META|LINK|HR|BR|PARAM|IMG|AREA|INPUT/irn var Stack = new Array(), posStack = new Array();rn while(true)rn var newone = re.exec(Foremost);rn if(newone == null) break;rn rn if(newone[1] == "")rn var Elem = newone[2];rn if(Elem.match(Singlable) && newone[3]!= "")rn continue;rn rn Stack.push(newone[2].toUpperCase());rn posStack.push(newone.index);rn rn if(newone[3] == "") break;rn elsern var StackTop = Stack[Stack.length-1];rn var End = newone[2].toUpperCase();rn if(StackTop == End)rn Stack.pop();rn posStack.pop();rn if(newone[3] == "")rn Foremost = Foremost+">";rn rn rn rn ;rn rn var cutpos = posStack.shift();rn Foremost = Foremost.substring(0,cutpos);rn rn return Foremost;rn
okhttp3实现注册登陆
注册 private void runRegist() throws InterruptedException { //处理注册逻辑 Thread t1 = new Thread(new Runnable() { @Override public void run() { RESULT
使用httpclient连接池来实现远程调用
在项目中,如果没有使用成熟的RPC框架又要实现简单的远程调用,那么httpClient是一个不错的选择。然是在使用httpClient的过程中,频繁的创建和销毁socket连接也是一个比较大的开销,将其封装成连接池会比较节约性能,直接上代码。   public class HttpConnectionManager { PoolingHttpClientConnectionManag...
求助,(ASP改用JS写)
文件如下rnrn rn rn"rn if left(strzt,1)="#" then rn zt1=split(strzt,"#")rn xb=trim(zt1(1))rn hy=trim(zt1(2))rn if xb="男" then ysxs=""rn strzt=trim(zt1(3))rn dfdq=trim(zt1(4))rn end ifrn if instr(online(i+3),"管理")=0 thenrn ls=""rn elsern ls=""rn end if rn if dfdq=dq then rn rens=rens+1rn %>rn rn rn rn rn <%rn end ifrn zongs=zongs+1rn end ifrnnext%>rnrnrn帮我把上边的语句转换成jsrnrn rn<%rnonline=application("hxf_c_onlinelist")rnfor i=1 to ubound(online) step 6rnif application("hxf_c_disnewuser")=1 or online(i+1)<>lyy thenrn strzt=online(i+2)rn ysxs=" ]');><%=ysxs%><%=online(i+1)%> <%=hy%> <%=ls%><%=online(i+3)%>
httpclient来测试本地接口
1.发送post请求接口 /** * 发送Post请求 * * @param httpPost * @return */ private static String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; ...
将EXCEL中宏的代码改用VB代码执行
将EXCEL中宏的代码改用VB代码执行,可以实现吗?有这方面知识的请改下
相关热词 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池 c#5.0 安装程序 c# 分页算法