我正在尝试获取请求中发送的确切JSON.这是我的代码:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
@Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
request.body().toString(), request.headers()));
com.squareup.okhttp.Response response = chain.proceed(request);
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client).build();
Run Code Online (Sandbox Code Playgroud)
但我只在日志中看到这个:
request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
Run Code Online (Sandbox Code Playgroud)
我怎么做正确的记录,考虑到拆除setLog()和setLogLevel()我们使用了改造1使用哪个?
我正在尝试使用Retrofit 2.0对服务器进行HTTP POST
MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG,90,byteArrayOutputStream);
profilePictureByte = byteArrayOutputStream.toByteArray();
Call<APIResults> call = ServiceAPI.updateProfile(
RequestBody.create(MEDIA_TYPE_TEXT, emailString),
RequestBody.create(MEDIA_TYPE_IMAGE, profilePictureByte));
call.enqueue();
Run Code Online (Sandbox Code Playgroud)
服务器返回错误,指出文件无效.
这很奇怪,因为我试图在iOS上使用相同的格式上传相同的文件(使用其他库),但它上传成功.
我想知道使用Retrofit 2.0上传图像的正确方法是什么?
在上传之前我应该先将它保存到磁盘吗?
谢谢!
PS:我已经将改造用于其他不包含图像的Multipart请求,并且已成功完成.问题是当我试图在主体中包含一个字节时.
我在Retrofit API中找不到用于记录完整请求/响应主体的相关方法.我期待在Profiler中提供一些帮助(但它只提供有关响应的元数据).我尝试在Builder中设置日志级别,但这对我没有帮助:
RestAdapter adapter = (new RestAdapter.Builder()).
setEndpoint(baseUrl).
setRequestInterceptor(interceptor).
setProfiler(profiler).
setClient(client).
setExecutors(MyApplication.getWebServiceThreadPool()).
setLogLevel(LogLevel.FULL).
setLog(new RestAdapter.Log() {
@Override
public void log(String msg) {
Log.i(TAG, msg);
}
}).
build();
Run Code Online (Sandbox Code Playgroud)
编辑:此代码现在正在运行.我不知道它为什么不提前工作.可能是因为我正在使用一些旧版本的改造.
最近我开始使用__CODE__,我遇到了解析空响应体的问题.我有一个服务器只响应http代码而没有响应体内的任何内容.如何只处理有关服务器响应的元信息(标题,状态代码等)?
提前致谢!
我正在使用Retrofit 2.0.0-beta1.
在测试中,我有一个替代方案,并期望错误HTTP 400
我想要retrofit.Response<MyError> response
但是response.body() == null
MyError没有反序列化 - 我只在这里看到它
response.errorBody().string()
Run Code Online (Sandbox Code Playgroud)
但它没有给我MyError作为对象
我将向我的服务器(它是Rails应用程序)发送一个简单的get方法,并使用RxJava和Retrofit获取结果.我做的是:
我的界面:
public interface ApiCall {
String SERVICE_ENDPOINT = "https://198.50.214.15";
@GET("/api/post")
io.reactivex.Observable<Post> getPost();
}
Run Code Online (Sandbox Code Playgroud)
我的模型是这样的:
public class Post
{
@SerializedName("id")
private String id;
@SerializedName("body")
private String body;
@SerializedName("title")
private String title;
public String getId ()
{
return id;
}
public String getBody ()
{
return body;
}
public String getTitle ()
{
return title;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在活动中所做的:
public class Javax extends AppCompatActivity {
RecyclerView rvListContainer;
postAdapter postAdapter;
List<String> messageList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_javax);
rvListContainer=(RecyclerView)findViewById(R.id.recyclerView);
postAdapter=new …Run Code Online (Sandbox Code Playgroud) Retrofit 2我目前正在使用,我想在我的服务器上传一些照片.我知道,旧版本使用TypedFile类进行上传.如果我们想要使用进度条,我们应该writeTo在TypedFile类中重写方法.
使用retrofit 2库时是否可以显示进度?
我是新手来改造2个库.我读了几篇文章作为初学者入门,我设法从RESTful API中获取XML数据而不指定参数.在我的方法中生成XML资源如下.
@GET
@Path("/foods")
@Produces(MediaType.APPLICATION_XML)
public List<FoodPyramid> getFoodPyramid() {
Session session = HibernateUtil.getSessionFactory().openSession();
trans = session.beginTransaction();
List<FoodPyramid> foodList = session.createQuery("from FoodPyramid").list();
try {
trans.commit();
session.close();
} catch (Exception e) {
session.close();
System.err.println("Food Pyramid fetch " + e);
}
System.err.println("Am in the food modal. . . . . . . .");
return foodList;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试在界面中传递参数时
@GET("user/{username}/{password}")
Call<List<UserCredentail>> getUserOuth(@Query("username") String username, @Query("password") String password);
Run Code Online (Sandbox Code Playgroud)
它无法运行,客户端没有收到任何数据.我花了一个星期试图通过使用非参数调用获取资源来修复它; 所以试着改变它
@GET("user/{username}/{password}")
Call<List<UserCredentail>> getUserOuth(@Path("username") String username, @Path("password") String password);
Run Code Online (Sandbox Code Playgroud)
它工作得很好.所以我的问题是:我什么时候需要在改造2中使用@Query和@Path注释?
我试图通过使用拦截器在Android中的Retrofit 2.0-beta3和OkHttpClient添加基于令牌的身份验证.但是当我在OkHttpClient中添加拦截器时,我得到UnsupportedOperationException.这是我的代码:在ApiClient.java中
public static TrequantApiInterface getClient(final String token) {
if( sTreqantApiInterface == null) {
Log.v(RETROFIT_LOG, "Creating api client for the first time");
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
sTreqantApiInterface = client.create(TrequantApiInterface.class);
}
return sTreqantApiInterface;
} …Run Code Online (Sandbox Code Playgroud) 我使用查询参数来设置Google Maps API所需的值.
问题是我不需要&第一个查询参数的符号.
@GET("/maps/api/geocode/json?")
Call<JsonObject> getLocationInfo(@Query("address") String zipCode,
@Query("sensor") boolean sensor,
@Query("client") String client,
@Query("signature") String signature);
Run Code Online (Sandbox Code Playgroud)
改造产生:
&address=90210&sensor=false&client=gme-client&signature=signkey
Run Code Online (Sandbox Code Playgroud)
当我需要它时,会导致调用失败
address=90210&sensor=false&client=gme-client&signature=signkey
Run Code Online (Sandbox Code Playgroud)
我该如何解决?