OkHttp 通常是异步的。常规调用如下所示:
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
// do something wih the result
}
}
}
Run Code Online (Sandbox Code Playgroud)
当消息到达时,只需对其执行一些操作即可。但我想用它作为阻塞吸气剂。就像是:
public void exampleMethod() {
MyDTO myDto = makeOkHttpCall.getData();
// do something with myDto Entity
}
Run Code Online (Sandbox Code Playgroud)
但我能找到的只是我可以将代码添加到onResponse(). 但这仍然是异步的。有什么想法如何改变这一点吗?
在 OkHttp 3.x 中,我们可以使用以下方式获取用户代理
\nimport okhttp3.internal.Version\n\nprintln(Version.userAgent())\nRun Code Online (Sandbox Code Playgroud)\n然而,这在 OkHttp 4.x 中不再起作用。
\nhttps://github.com/square/okhttp/issues/5969中提出了一个问题,并在https://github.com/square/okhttp/pull/5981中修复中修复,但我无法解决工作。
\n变更日志中指出从 4.7.0 版本开始。
\nNew: Constant string okhttp3.VERSION. This is a string like \xe2\x80\x9c4.5.0-RC1\xe2\x80\x9d, \xe2\x80\x9c4.5.0\xe2\x80\x9d, or \xe2\x80\x9c4.6.0-SNAPSHOT\xe2\x80\x9d indicating the version of OkHttp in the current runtime. Use this to include the OkHttp version in custom User-Agent headers.\nRun Code Online (Sandbox Code Playgroud)\n但我就是无法导入okhttp3.VERSION
我想连接我的本地服务器并使用Retrofit获取一些数据,但我给出了错误“无法解析 TLS 数据包标头”,并且我无法解决此问题,请给我一个解决方案
onFailure:无法解析 TLS 数据包标头
ServiceBuilder.kt
object ServiceBuilder {
private val client = OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.MODERN_TLS) )
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(Config().BASE_URL)# "https://10.0.2.2:5000"
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T{
Security.insertProviderAt(Conscrypt.newProvider(), 1);
return retrofit.create(service)
}
}
Run Code Online (Sandbox Code Playgroud)
LinesrsEndpoint.kt
interface LinesrsEndpoint{
@GET("/getAllLinesrs")
fun getLinesrs(): Call<AllLinesrs>
}
Run Code Online (Sandbox Code Playgroud)
线路Rs.kt
data class AllLinesrs(val results:List<Linesrs>)
data class Linesrs(
var lineId: Int,
var symbolId: String,
var lineStart: String,
var lineEnd: String,
var lineTimeFrame: String,
var lineInsertTime: String,
var lineSensDgre: String,
var linesrsGroupId: String, …Run Code Online (Sandbox Code Playgroud) 我正在使用 Postman 版本 8.5.1,并且我正在尝试使用代码 OkHTTP 代码片段。似乎有些声明不起作用......
OkHttpClient client = new OkHttpClient().newBuilder().build();
Run Code Online (Sandbox Code Playgroud)
然而这似乎有效......
OkHttpClient client = new OkHttpClient();
Run Code Online (Sandbox Code Playgroud)
这也行不通...
.addFormDataPart("file","test.jpg",RequestBody.create(MediaType.parse("application/octet-stream"),new File("/Users/tm/Desktop/test.jpg")))
Run Code Online (Sandbox Code Playgroud)
它提到了一些关于错误的 RequestBody 对象的信息......
我正在使用这个 Maven 仓库...
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
这是导入声明
import com.squareup.okhttp.*;
Run Code Online (Sandbox Code Playgroud)
哪个版本的 okhttp 与 Postman 代码片段完全兼容?应该使用哪个 Maven 存储库?
好像还有一个 okhttp3 ...
编辑我能够构建我的 OkHttp 客户端,其中包含 Client.SSLContext.KeyManager 中的客户端证书和 Client.SSLContext.TrustManager 中的受信任证书
// Create keyManagerFactory with keystore.jks
KeyStore clientStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientStore.load(new FileInputStream(new File("keystore.jks")), storePassword.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientStore, storePassword.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
// Create trustManagerFactory with default cacerts truststore
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
trustManager = trustManagers[0];
// Create sslContext from keyManagers (from custom keystore with client key) …Run Code Online (Sandbox Code Playgroud) 我尝试将 api 与 OAuth2 结合使用。有了邮差就可以了。但现在我尝试用Java 来写这个。我没有 spring boot,它是一个简单的 Maven 项目我发现的唯一示例是这个
但它似乎只适用于基本身份验证。
我的问题是,是否可以使用 okhttp 进行 Oauth2?或者是错误的库?
我正在尝试从 okhttp 转换此响应:
[
{
"word": "Auricomous",
"definition": "Having golden or blond hair ",
"pronunciation": "Aurikomous"
}
]
Run Code Online (Sandbox Code Playgroud)
使用此代码:
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://random-words-api.vercel.app/word")
.get()
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Get response body
ObjectMapper objectMapper = new ObjectMapper();
String responseBody = response.body().toString();
Root[] root = objectMapper.readValue(responseBody, Root[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)
数据传输对象:
public class Root{
public String …Run Code Online (Sandbox Code Playgroud) 我正在使用OKHttp对服务器执行Post请求,如下所示:
public class NetworkManager {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, JSONObject json) throws IOException {
try {
JSONArray array = json.getJSONArray("d");
RequestBody body = new FormEncodingBuilder()
.add("m", json.getString("m"))
.add("d", array.toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (JSONException jsone) {
return "ERROR: " + jsone.getMessage();
}
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
NetworkManager manager = new NetworkManager();
String response = manager.post("http://www.example.com/api/", jsonObject); …Run Code Online (Sandbox Code Playgroud) 我正在使用okhttp库发送请求来休息api.这是我发送请求的java代码https:
RequestBody body = RequestBody.create(JSON, requestBody);
Request request = new Request.Builder().url("https://examplesite.com/json/").post(body)
.addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
.addHeader("Accept-Encoding", "gzip").addHeader("Accept-Language", "en-US,en;q=0.8,fa;q=0.6,ar;q=0.4")
.build();
Response response = client.newCall(request).execute();
String res = new String(response.body().string().getBytes("UTF-8"));
System.out.println(res);
Run Code Online (Sandbox Code Playgroud)
该res变量是:?CU8{$???'L?@R?W*?$??b?H?E?l?K?C? 30??}c&,p??q???)+3?R?28???#SC?
上面文字的编码是什么?
这是响应头:
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,fa;q=0.6,ar;q=0.4
Connection:keep-alive
Content-Length:95
Content-Type:application/json
Run Code Online (Sandbox Code Playgroud)
我无法理解响应体的编码是什么.无论何时我通过邮递员在Chrome上发送请求,响应正文是一个普通的json.参加该协议https,我认为okhttp库处理加密和描述数据.
我正在学习okhttp,我想在我的计算机或Android设备上使用本地json文件进行测试.但我不知道如何访问本地文件作为url字符串来调用该函数.像这样:
File sdcard = Environment.getExternalStorageDirectory();
File testJson = new File(sdcard, "test.json");
HttpUtils.HttpGet(testJson., mCallback);
public class HttpUtils {
private static final String TAG = "HttpUtils";
private static final OkHttpClient mClient = new OkHttpClient();
public static void HttpGet(String url, Callback callback) {
//????Request
final Request request = new Request.Builder()
.url(url)
.build();
//????Call
Call call = mClient.newCall(request);
//??????
call.enqueue(callback);
}
}
Run Code Online (Sandbox Code Playgroud)