1、okhttp框架使用手机网络为什么不能访问服务器
POST TO A SERVER
Posting a String:
public static final MediaType jsonReq
= MediaType.parse(application/json; charset=utf-8);
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(jsonReq, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Posting Streaming:
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse(text/x-markdown; charset=utf-8);
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(Numbers
);
sink.writeUtf8(-------
);
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format( * %s = %s
, i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + × + i;
}
return Integer.toString(n);
}
};
Request request = new Request.Builder()
.url(https://api.github.com/markdown/raw)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(Unexpected code + response);
System.out.println(response.body().string());
}
Posting a File:
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse(text/x-markdown; charset=utf-8);
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File(README.md);
Request request = new Request.Builder()
.url(https://api.github.com/markdown/raw)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(Unexpected code + response);
System.out.println(response.body().string());
}
Posting from parameters:
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
.add(search, Jurassic Park)
.build();
Request request = new Request.Builder()
.url(https://en.wikipedia.org/w/index.php)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(Unexpected code + response);
System.out.println(response.body().string());
}
Posting a multipart request:
private static final String IMGUR_CLIENT_ID = ...;
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse(image/png);
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of(Content-Disposition, form-data; name= itle),
RequestBody.create(null, Square Logo))
.addPart(
Headers.of(Content-Disposition, form-data; name=image),
RequestBody.create(MEDIA_TYPE_PNG, new File(website/static/logo-square.png)))
.build();
Request request = new Request.Builder()
.header(Authorization, Client-ID + IMGUR_CLIENT_ID)
.url(https://api.imgur.com/3/image)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(Unexpected code + response);
System.out.println(response.body().string());
}
Posing Json with Gson
private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();
public void run() throws Exception {
Request request = new Request.Builder()
.url(https://api.github.com/gists/c2a7c39532239ff261be)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException(Unexpected code + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
static class Gist {
Map files;
}
static class GistFile {
String content;
}
Response Caching:
为了缓存响应,你需要一个你可以读写的缓存目录,和缓存大小的限制。这个缓存目录应该是私有的,不信任的程序应不能读取缓存内容。
一个缓存目录同时拥有多个缓存访问是错误的。大多数程序只需要调用一次 new OkHttp() ,在第一次调用时配置好缓存,然后其他地方只需要调用这个实例就可以了。否则两个缓存示例互相干扰,破坏响应缓存,而且有可能会导致程序崩溃。
响应缓存使用HTTP头作为配置。你可以在请求头中添加 Cache-Control: max-stale=3600 ,OkHttp缓存会支持。你的服务通过响应头确定响应缓存多长时间,例如使用 Cache-Control: max-age=9600 。
2、android okhttp怎么给服务器传递的参数怎么转成json
public String androidPost() { String rs = null; String path = "url/Android_JDBC_SH/AndroidLoginAction"; HttpPost hp = new HttpPost(path); //获取客户端,用来向服务器发出请求 DefaultHttpClient hc = new DefaultHttpClient(); try { //Default Constructor taking a name and a value BasicNameValuePair nm = new BasicNameValuePair("name", name); BasicNameValuePair pa = new BasicNameValuePair("password", password); List list = new ArrayList(); list.add(nm); list.add(pa); //构建向服务器发送的实体 HttpEntity entity = new UrlEncodedFormEntity(list); hp.setEntity(entity); //提交请求,获取服务器的响应 HttpResponse response = hc.execute(hp); if (response.getStatusLine().getStatusCode() == 200) { //获取响应实体 entity = response.getEntity(); rs = EntityUtils.toString(entity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rs; }
3、android 用okhttp访问服务器的数据为什么总连接不上
OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。
OkHttp 处理了很多网络疑难杂症:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果你用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。
4、Android通过OKhttp从服务器端获取数据
①简单的异步Get请求
第一步,创建OKHttpClient对象
第二步,创建Request请求
第三步,创建一个Call对象
第四步,将请求添加到调度中
不多说,直接上代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//okHttp的基本使用 --- get方法
String url = "https://api.douban.com/v2/movie/top250?start=0&count=10";
//1,创建OKHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//2,创建一个Request
Request request = new Request.Builder().url(url).build();
//3,创建一个call对象
Call call = mOkHttpClient.newCall(request);
//4,将请求添加到调度中
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
final String message = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
tv_message.setText(message);
progressBar.setVisibility(View.GONE);
}
});
}
}
});
5、Okhttp怎样使用post向服务器提交数组
public String androidPost() { String rs = null; String path = "url/Android_JDBC_SH/AndroidLoginAction"; HttpPost hp = new HttpPost(path); //获取客户端,用来向服务器发出请求 DefaultHttpClient hc = new DefaultHttpClient(); try { //Default Constructor taking a name and a value BasicNameValuePair nm = new BasicNameValuePair("name", name); BasicNameValuePair pa = new BasicNameValuePair("password", password); List list = new ArrayList(); list.add(nm); list.add(pa); //构建向服务器发送的实体 HttpEntity entity = new UrlEncodedFormEntity(list); hp.setEntity(entity); //提交请求,获取服务器的响应 HttpResponse response = hc.execute(hp); if (response.getStatusLine().getStatusCode() == 200) { //获取响应实体 entity = response.getEntity(); rs = EntityUtils.toString(entity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rs; }
6、android okhttp3怎么判断服务器请求地址错误
找到SQL Sever服务。在计来算机管理源框里找到Sql sever配置管理器找到Sql Sever服务打开服务,这里有几种服务,这些服务都是自己安装数据库时装上的。
打开启动SQL Sever服务。右键点击服务,这里要看清楚什么才是服务,小技巧:服务器的图标是一个库的样式,启动它就可以了。
SQL文件目录启动服务(二)
找到SQL安装目录。点击【开始】--【所有文件】--【Microsoft SQL Server 2008】--【配置工具】--【SQL Server 配置管理器】。
7、android rxjava retrofit okhttp 怎么给服务器传值
get请求可以这么写
@GET("/app/devices")
Observable<DeviceBean> getDevice(@Query("token") String token);
token就是传的值
post请求这么写
@POST("/app/devices")
Observable<MeetingRoomOccupy> getDevice(@Body DeviceBean data);
DeviceBean里的值就是post的传值,会将DeviceBean里的变量名作为key值,值作为value
8、可以在服务器端使用okhttp吗
有源码都不是问题
9、android使用okhttp 向服务器post怎样传
public String androidPost() { String rs = null; String path = "url/Android_JDBC_SH/AndroidLoginAction"; HttpPost hp = new HttpPost(path); //获取客户端,用来向服务器发出请求 DefaultHttpClient hc = new DefaultHttpClient(); try { //Default Constructor taking a name and a value BasicNameValuePair nm = new BasicNameValuePair("name", name); BasicNameValuePair pa = new BasicNameValuePair("password", password); List list = new ArrayList(); list.add(nm); list.add(pa); //构建向服务器发送的实体 HttpEntity entity = new UrlEncodedFormEntity(list); hp.setEntity(entity); //提交请求,获取服务器的响应 HttpResponse response = hc.execute(hp); if (response.getStatusLine().getStatusCode() == 200) { //获取响应实体 entity = response.getEntity(); rs = EntityUtils.toString(entity); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rs; }