HttpRequest 访问网络的部分代码
/**
*
* @param url 地址
* @param xml 参数
* @return
*/
public static String response(String url, String xml) {
HttpPost httpRequest = new HttpPost(url);
try {
StringEntity xmlse = new StringEntity(xml, "UTF-8");
xmlse.setContentType("text/xml");
httpRequest.setEntity(xmlse);
httpRequest.setHeader("Content-Type",
"application/soap+xml;charset=UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
KLog.e(e1.toString());
}
...
}
Retofit 代码代替上面的HttpRequest代码
//Headers里的内容是httpRequest里来的
@Headers({"Content-Type:application/soap+xml;charset=UTF-8"})
@POST("xxx/xxx/xxx.xxx")
Observable<String> request(@Body RequestBody body);
部分代码:
配置retrofit
retrofit = new Retrofit.Builder().baseUrl(Constants_api.BASE_URL)
.client(new OkHttpClient())
//不知道 StringConverterFactory是不是必须的,没细测
.addConverterFactory(StringConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
使用
使用的话正常使用,传RequestBody类型的参数进去就行了
//"text/xml" 是根据httpRequest那边来的
new RequestBody.create(MediaType.parse("text/xml"), str);
StringConverterFactory(自己瞎写的,勿喷)
public class StringConverterFactory extends Converter.Factory{
private StringConverterFactory() {
}
public static StringConverterFactory create(){
return new StringConverterFactory();
}
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
return new StringResponseBodyConverter();
}
}
StringResponseBodyConverter
public final class StringResponseBodyConverter implements Converter<ResponseBody, String> {
@Override
public String convert(ResponseBody value) throws IOException {
InputStream reader = null;
try {
reader = value.byteStream();
ByteArrayOutputStream writer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 2];
int size = -1;
while ((size = reader.read(buffer)) > 0) {
writer.write(buffer, 0, size);
}
String result = new String(writer.toByteArray());
return result;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}