许多例子显示添加标题应该:
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
Run Code Online (Sandbox Code Playgroud)
但我想动态添加标题作为用户的标题要求,我该如何实现它?
Headers h = new Headers.Builder().build();
for (HttpHeader hh : ht.HttpRequestHeader) {
h.newBuilder().add(hh.Name, hh.Value);
} //<<---Nothing changed!!!!!
Run Code Online (Sandbox Code Playgroud) 我在服务器中有CPUx2并且我有一个包含许多线程的程序,如果所有线程需要很长时间才能执行某些操作,是否可以使用Thread.Sleep(10)以便让CPU将作业释放到另一个线程中?我可以只使用thread.sleep并让CPU自动切换另一个线程以改善或提高性能吗?
在2016/06/06更新:每个线程都专注于从Executors获取来自Internet的HTTP内容,而我想让它延迟更多时间,但我不确定何时添加TimeUnit.MILLISECONDS.sleep(10 )在代码里面是使用MILLISECONDS还是NANOSECOND以及有多少时隙让CPU自动切换另一个线程,这样整体性能可以公平:
@Override
public void run() {
//this.RunActual = System.currentTimeMillis();
if ("Started".equals(this.JobStatus)) {
String startDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
System.out.println(this.HttpRequestAddress + " has started at " + startDate);
try {
this.url = new URL("http://" + this.HttpRequestAddress + ":" + this.HttpRequestPort);
this.conn = (HttpURLConnection) this.url.openConnection();
this.conn.setRequestMethod(this.HttpRequestMethod);
this.conn.setReadTimeout(this.HttpRequestReadTimeout);
this.conn.setConnectTimeout(this.HttpRequestConnectionTimeout);
this.conn.setInstanceFollowRedirects(false);
for (HttpHeader hh : this.HttpRequestHeader) {
this.conn.setRequestProperty(hh.Name, hh.Value);
}
this.conn.connect();
this.responseCode = 0;
this.responseCode = this.conn.getResponseCode();
System.out.println(this.HttpRequestAddress + " has response header " + this.conn.getHeaderFields().toString());
if (this.responseCode == HttpURLConnection.HTTP_OK) {
if …Run Code Online (Sandbox Code Playgroud) 我知道Java的ByteBuffer.clear()并不是真的要清除ByteBuffer中的所有数据,所以当我每次都使用StringBuilder.append()字符串时,最终结果总是在ByteBuffer中附加所有剩余的字符,这是旧的数据.写,所以如何解决这个问题?
int byteRead = -1;
int readCount = 0;
int BUFFER_SIZE = 256;
StringBuilder sb = new StringBuilder();
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
ReadableByteChannel readableByteChannel = Channels.newChannel(is);
while ((byteRead = readableByteChannel.read(buffer)) > 0 && readCount < 68) {
sb.append(new String(buffer.array(), "UTF-8"));
buffer.clear();
readCount++;
}
Run Code Online (Sandbox Code Playgroud)