标签: okhttp

如何使用okhttp上传文件?

我使用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)

我的问题是:

  1. 如何设置部件名称?在表单中,该文件应命名为file1.
  2. 如何在表单中添加其他字段?

java android okhttp mimecraft

35
推荐指数
3
解决办法
6万
查看次数

如何在Android中使用okhttp库向api(http post)添加参数

在我的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)

android okhttp

35
推荐指数
4
解决办法
4万
查看次数

使用OKHTTP跟踪多部分文件上载的进度

我正在尝试实现一个进度条来指示多部分文件上载的进度.

我已经阅读了对这个答案的评论 - /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)

android okhttp okio

35
推荐指数
2
解决办法
2万
查看次数

Retrofit中的SocketTimeoutException

我试图向服务器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)

android socket-timeout-exception retrofit okhttp

35
推荐指数
3
解决办法
4万
查看次数

Android Picasso库,如何添加身份验证标头?

我尝试使用自定义身份验证器设置自定义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)

谢谢!

android picasso okhttp

33
推荐指数
2
解决办法
2万
查看次数

改造和OkHttp基本认证

我正在尝试将基本身份验证(用户名和密码)添加到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 okhttp retrofit2

32
推荐指数
2
解决办法
3万
查看次数

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请求吗?

android retrofit okhttp

31
推荐指数
4
解决办法
3万
查看次数

通过OkHttp拦截器拦截和重试呼叫

我需要在里面重试请求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)

java interceptor retrofit okhttp

31
推荐指数
1
解决办法
1万
查看次数

改造 - 全球拦截响应

我想拦截改装引擎收到的所有响应,并扫描HTTP错误代码,例如错误403.

我知道我可以使用每个请求的失败(RetrofitError错误)回调并检查403,但我想全局包装响应.

我可以看到请求拦截是可能的,但我没有看到类似的响应选项.

有什么建议?

android retrofit okhttp

31
推荐指数
1
解决办法
2万
查看次数

Retrofit 2示例教程但GsonConverterFactory显示错误"无法解析符号"

我正在尝试遵循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)

android gson android-library retrofit okhttp

31
推荐指数
3
解决办法
3万
查看次数