我使用okhttp作为我的httpclient.我认为这是一个很好的api,但文档并不那么详细.
如何使用它来发送带文件上传的http帖子请求?
public Multipart createMultiPart(File file){
Part part = (Part) new Part.Builder().contentType("").body(new File("1.png")).build();
//how to set part name?
Multipart m = new Multipart.Builder().addPart(part).build();
return m;
}
public String postWithFiles(String url,Multipart m) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
m.writeBodyTo(out)
;
Request.Body body = Request.Body.create(MediaType.parse("application/x-www-form-urlencoded"),
out.toByteArray());
Request req = new Request.Builder().url(url).post(body).build();
return client.newCall(req).execute().body().string();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
在我的Android应用程序中,我使用的是okHttp库.如何使用okhttp库将参数发送到服务器(api)?目前我使用以下代码访问服务器现在需要使用okhttp库.
这是我的代码:
httpPost = new HttpPost("http://xxx.xxx.xxx.xx/user/login.json");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID));
nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord));
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());
Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个进度条来指示多部分文件上载的进度.
我已经阅读了对这个答案的评论 - /sf/answers/1699994341/,我必须将传递给传递给RequestBody的接收器包装起来并提供跟踪移动的字节的回调.
我已经创建了一个自定义RequestBody并使用CustomSink类包装了接收器,但是通过调试我可以看到字节是由RealBufferedSink ln 44 编写的,而自定义接收器写入方法只运行一次,不允许我跟踪移动的字节数.
private class CustomRequestBody extends RequestBody {
MediaType contentType;
byte[] content;
private CustomRequestBody(final MediaType contentType, final byte[] content) {
this.contentType = contentType;
this.content = content;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public long contentLength() {
return content.length;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
CustomSink customSink = new CustomSink(sink);
customSink.write(content);
}
}
private class CustomSink implements BufferedSink {
private static final String TAG = "CUSTOM_SINK"; …Run Code Online (Sandbox Code Playgroud) 我试图向服务器POST请求获取数据,但有时它发生了SocketTimeoutException!
我曾经Ok3Client解决它,但我面临同样的例外如何解决它?
我的代码如下
public void getNormalLogin() {
if (mProgressDialog == null) {
mProgressDialog = ViewUtils.createProgressDialog(mActivity);
mProgressDialog.show();
} else {
mProgressDialog.show();
}
if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
restadapter = new RestAdapter.Builder().setEndpoint(HOST).setLogLevel(RestAdapter.LogLevel.FULL).setClient(new Ok3Client(new OkHttpClient())).build();
mApi = restadapter.create(Api.class);
mApi.SignIn(etEmail.getText().toString(), etPassword.getText().toString(), new Callback<ArrayList<SignUpMainBean>>() {
@Override
public void success(ArrayList<SignUpMainBean> signUpMainBeen, Response response) {
mProgressDialog.dismiss();
LOGD("Status:: ::", String.valueOf(response.getStatus()));
LOGD("Code:: ::", String.valueOf(signUpMainBeen.get(0).getCode()));
if (signUpMainBeen != null && signUpMainBeen.size() > 0) {
if (signUpMainBeen.get(0).getCode() == 1) {
for …Run Code Online (Sandbox Code Playgroud) 我尝试使用自定义身份验证器设置自定义OkHttpClient,但是正如文档所说:"响应来自远程Web或代理服务器的身份验证挑战." 我必须为每个图像发出2个请求,这并不理想.
有像Retrofit这样的请求拦截器吗?或者我在OkHttpClient中遗漏了什么?
我正在使用最新版本:
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.okhttp:okhttp:2.0.+'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.+'
compile 'com.squareup.okio:okio:1.0.0'
Run Code Online (Sandbox Code Playgroud)
谢谢!
我正在尝试将基本身份验证(用户名和密码)添加到Retrofit OkHttp客户端.这是我到目前为止的代码:
private static Retrofit createMMSATService(String baseUrl, String user, String pass) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Retrofit 2.2,本教程建议使用AuthenticationInterceptor,但此类不可用.添加凭据的正确位置在哪里?我是否必须将它们添加到我的拦截器,客户端或Retrofit对象中?我该怎么做?
我正在尝试在Android上探索Retrofit + OkHttp.这是我在网上找到的一些代码:
RestAdapter restAdapter = new RestAdapter.Builder().setExecutors(executor, executor)
.setClient(new OkClient(okHttpClient))
.setServer("blah").toString())
.build();
Run Code Online (Sandbox Code Playgroud)
如果我不使用执行程序服务,我的代码是否会在主线程上运行?我应该在新线程中发出Web请求吗?
我需要在里面重试请求OkHttp Interceptor.例如,存在需要Authorization令牌的传入请求.如果Authorization令牌已过期,则服务器返回带403代码的响应.在这种情况下,我正在检索一个新令牌并尝试使用相同的chain对象再次进行调用.
但是OkHttp会抛出一个异常,它声明你不能用同一个chain对象发出两个请求.
java.lang.IllegalStateException: network interceptor org.app.api.modules.ApplicationApiHeaders@559da2 must call proceed() exactly once
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个干净的解决方案来解决内部重试网络请求的问题OkHttp Interceptor?
谢谢
public final class ApplicationApiHeaders implements Interceptor {
private static final String AUTHORIZATION = "Authorization";
private TokenProvider mProvider;
public ApplicationApiHeaders(TokenProvider provider) {
mProvider = provider;
}
@Override
public Response intercept(Chain chain) throws IOException {
Token token = mProvider.getApplicationToken();
String bearerToken = "Bearer " + token.getAccessToken();
System.out.println("Token: " + bearerToken);
Request request = …Run Code Online (Sandbox Code Playgroud) 我想拦截改装引擎收到的所有响应,并扫描HTTP错误代码,例如错误403.
我知道我可以使用每个请求的失败(RetrofitError错误)回调并检查403,但我想全局包装响应.
我可以看到请求拦截是可能的,但我没有看到类似的响应选项.
有什么建议?
我正在尝试遵循Retrofit的2 教程,但是在这部分代码中有一个GsonConverterFactory显示错误Cannot resolve symbol:
public class ServiceGenerator {
public static final String API_BASE_URL = "http://your.api-base.url";
private static OkHttpClient httpClient = new OkHttpClient();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
//THIS IS THE LINE WITH ERROR!!!!!!!!!!!!
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
Run Code Online (Sandbox Code Playgroud)
之前我在gradle.build中添加了,我不确定是否应该添加GSON,因为他们说Retrofit 1.9有它但是没有提到Retrofit 2:
dependencies {
// Retrofit & OkHttp
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
}
Run Code Online (Sandbox Code Playgroud)