java okhttp动态地使用for循环添加头文件

时间:2016-06-11 01:44:38

标签: java http-headers okhttp okhttp3

许多示例显示添加标题:

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();

但我想动态添加标题作为用户的标题要求,我该如何实现呢?

Headers h = new Headers.Builder().build();
for (HttpHeader hh : ht.HttpRequestHeader) {
    h.newBuilder().add(hh.Name, hh.Value);
}  //<<---Nothing changed!!!!!

1 个答案:

答案 0 :(得分:8)

Headers.Builder builder = new Headers.Builder();
for (HttpHeader hh : ht.HttpRequestHeader) {
  builder.add(hh.Name, hh.Value);
}
Headers h = builder.build();