简体   繁体   English

当Content-Type = application / octet-stream时,Android如何处理改造响应?

[英]Android how to handle retrofit response when Content-Type = application/octet-stream?

retrofit request interface: 改造请求界面:

public interface IDataService {
      // Request URL:             https://demo.testdata.com/getData/order?timeStamp=1491986181670&callerId=android_platform
      // Request Method:          GET
      // Response Content-Type:   application/octet-stream
      @GET("https://demo.testdata.com/getData/" + "{type}")
      Observable<Response> getTestData(@Path(value = "type", encode = false) String type
              , @Query("callerId") String callerId, @Query("timeStamp") long timeStamp);
  }

Use the retrofit request interface: 使用改造请求界面:

In TestActivity.java 在TestActivity.java中

public Observable<String> getTestData(IDataService dataService) {
        final BehaviorSubject<String> subject = BehaviorSubject.create();
        if (null == dataService) {
            subject.onError(new NullPointerException());
            return subject;
        }

        bindObservable(dataService.getTestData("order", "android_platform", new Date().getTime())).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Response>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        subject.onError(e);
                    }

                    @Override
                    public void onNext(retrofit.client.Response response) {
                        // TODO: how to handle the response body content?
                        // In general, response is  json string. Then  parse and convert json string to Object.
                        // Now Response Content-Type = application/octet-stream, How to handle it?

                    }
                });
        return subject.asObservable();
    }

Question: In general, response Content-Type=application/json, parse JSON string to Object. 问题:通常,响应Content-Type = application / json,将JSON字符串解析为Object。 Now,Response Content-Type = application/octet-stream, How to handle it? 现在,Response Content-Type =应用程序/八位字节流,如何处理?

Ref: 参考:

  • com.squareup.retrofit:retrofit:1.9.0 com.squareup.retrofit:retrofit:1.9.0
  • io.reactivex:rxjava:1.1.0 io.reactivex:rxjava:1.1.0
  • io.reactivex:rxandroid:1.1.0 io.reactivex:rxandroid:1.1.0

Moved solution from question to answer: 解决方案从问题移到答案:

Solution: 解:

I had solved the problem. 我已经解决了问题。 The brief description for the solution is below : 解决方案的简要说明如下:

Retrofit Response -> InputStream ->java bytes[] -> treat byte as short or int -> int[] or short[]. 改造响应-> InputStream-> java bytes []->将字节视为short或int-> int []或short []。

Code

Below is my detail demo code. 以下是我的详细演示代码。

Android App client, which receiver 8-bit unsigned integer array. Android App客户端,该客户端接收8位无符号整数数组。

IRetrofitService.java IRetrofitService.java
  public class IRetrofitService { // Local Node.JS Server /** * FAQ: Retrofit: java.net.ConnectException: Connection refused * Reason:Node.js server PI is http://127.0.0.1:8888/. * If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8888/ . Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address Ref: https://stackoverflow.com/questions/5495534/java-net-connectexception-localhost-127-0-0-18080-connection-refused */ private static final String PATH = "http://10.0.2.2:8888"; public interface ApiManagerService { @GET("/") @Headers("Content-Type:application/octet-stream") Observable<Response> getUnsignedBytes(); } private static final RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(PATH).setLogLevel(RestAdapter.LogLevel.FULL).build(); public static final ApiManagerService apiManager = restAdapter.create(ApiManagerService.class); } 
RetrofitDemoActivity.java RetrofitDemoActivity.java
 import android.util.Log; import android.widget.Toast; import com.hades.android.example.R; import com.hades.android.example.framework.BaseActivity; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import butterknife.OnClick; import retrofit.client.Response; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * RxJava and RxAndroid , Retrofit to request data from server. * Need <uses-permission android:name="android.permission.INTERNET" /> */ public class RetrofitDemoActivity extends BaseActivity { public static final String TAG = RetrofitDemoActivity.class.getSimpleName(); private int[] singedBytes; // TODO: IRetrofitService.apiManager.getUnsignedBytes() private Observable<Response> getUnsignedBytes() { return IRetrofitService.apiManager.getUnsignedBytes(); } @OnClick(R.id.requestUnsignedBytes) public void requestUnsignedBytes() { Log.d(TAG, "requestUnsignedBytes,----->"); bindObservable(getUnsignedBytes()).observeOn(Schedulers.io()).subscribe(new Subscriber<Response>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } /** * Response content is 8 bites unsigned byte * [246, 254, 255, 0, 10, 126, 127, 128, 129, 253, 254, 255, 0, 1, 232] */ /** s,buf_size=15,read_buf_size=15 start parse origin = -10, afterTransValue = 246 origin = -2, afterTransValue = 254 origin = -1, afterTransValue = 255 origin = 0, afterTransValue = 0 origin = 10, afterTransValue = 10 origin = 126, afterTransValue = 126 origin = 127, afterTransValue = 127 origin = -128, afterTransValue = 128 origin = -127, afterTransValue = 129 origin = -3, afterTransValue = 253 origin = -2, afterTransValue = 254 origin = -1, afterTransValue = 255 origin = 0, afterTransValue = 0 origin = 1, afterTransValue = 1 origin = -24, afterTransValue = 232 end parse */ @Override public void onNext(Response response) { InputStream inputStream = null; BufferedInputStream bufferedInputStream = null; try { inputStream = response.getBody().in(); bufferedInputStream = new BufferedInputStream(inputStream); int buf_size = inputStream.available(); byte[] bytes = new byte[buf_size]; int read_buf_size = bufferedInputStream.read(bytes, 0, buf_size); Log.d(TAG, "requestUnsignedBytes,buf_size=" + buf_size + ",read_buf_size=" + read_buf_size); if (null == bytes) { return; } if (null != singedBytes) { singedBytes = null; } singedBytes = new int[buf_size]; Log.d(TAG, "requestUnsignedBytes, start parse"); for (int i = 0; i < bytes.length; i++) { /** * First, read as the 8 bites signed byte. * Second, get the signed tag as the value. */ byte origin = bytes[i]; int afterTransValue = 0xFF & origin; Log.d(TAG, "requestUnsignedBytes,origin = " + bytes[i] + ", afterTransValue = " + afterTransValue); singedBytes[i] = afterTransValue; } Log.d(TAG, "requestUnsignedBytes, end parse"); } catch (IOException e) { e.printStackTrace(); } finally { } } }); } } 

Node.JS is as demo server,which reponse 8-bit unsigned integer array. Node.JS作为演示服务器,它响应8位无符号整数数组。

server.js server.js
 var http = require('http'); var server = http.createServer(function (request, response) { var sampleBytes = new Uint8Array(15); sampleBytes[0] = -10; sampleBytes[1] = -2; sampleBytes[2] = -1; sampleBytes[3] = 0; sampleBytes[4] = 10; sampleBytes[5] = 126; sampleBytes[6] = 127; sampleBytes[7] = 128; sampleBytes[8] = 129; sampleBytes[9] = 253; sampleBytes[10] = 254; sampleBytes[11] = 255; sampleBytes[12] = 256; sampleBytes[13] = 257; sampleBytes[14] = 1000; console.log(sampleBytes); var buffer = new Buffer(sampleBytes); response.writeHead(200,{'Access-Control-Allow-Origin':'*','Access-Control-Allow-Method':'GET,POST','Content-Type':'application/octet-stream'}); response.write(buffer); response.end(); }); server.listen(8888,"localhost",function(){ console.log("start monitor..."); }); console.log('Server running at http://127.0.0.1:8888/'); 

Ref: 参考:

  • com.squareup.retrofit:retrofit:1.9.0 com.squareup.retrofit:retrofit:1.9.0
  • io.reactivex:rxjava:1.1.0 io.reactivex:rxjava:1.1.0
  • io.reactivex:rxandroid:1.1.0 io.reactivex:rxandroid:1.1.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Android POST在ResponseEntity中没有返回类型application / octet-stream - Spring Android POST no return type application/octet-stream in ResponseEntity 解码应用程序/八位字节流 - Decode application/octet-stream 发送到php上传图片文件的Android图片文件是application / octet-stream类型而不是image / jpeg? - Android image file sent to php upload image file is application/octet-stream type and not image/jpeg? 应用程序/八位流-Android - Applilation/Octet-Stream - Android 如何使用 mediaCodec 解码器解码具有 mime 类型应用程序/八位字节流的视频 - How to decode video with mime type application/octet-stream using mediaCodec decoder Java MimetypesFileTypeMap 总是在 Android 模拟器上返回应用程序/八位字节流 - Java MimetypesFileTypeMap always returning application/octet-stream on Android emulator 如何将上传的 jpg 类型设置为“image/jpg”而不是“application/octet-stream” - How to set uploaded jpg type to be recognised as "image/jpg" instead of "application/octet-stream" 如何在Android中将HTTP POST与“ application / octet-stream”一起使用? (Microsoft认知视频) - How to use HTTP POST with “application/octet-stream” in Android? (Microsoft Cognitive Video) android如何在响应中使用HttpURLConnection(Content-Type:text / html)? - How to use HttpURLConnection with Response (Content-Type: text/html ) in android? Android 恶意软件样本采用二进制格式(八位字节流)。 如何将其转换回普通文件以供分析? - Android malware samples come in binary format (octet-stream). How to convert it back to normal file for analysis?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM