導航:首頁 > IDC知識 > okhttp伺服器

okhttp伺服器

發布時間:2020-10-13 08:51:52

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; }

與okhttp伺服器相關的知識