You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.example.share2;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
public class ConnectServer {
public Headers getHeaders(Map<String, String> mapAdd){
//头部只有基本参数appSecret,appId,要要想添加其他参数使用
Map<String, String> headers_map = new HashMap<>();
headers_map.put("appSecret", Constants.appSecret);
headers_map.put("appId", Constants.appId);
Headers.Builder builder_header = new Headers.Builder();
if(!mapAdd.isEmpty()){
for (String key:mapAdd.keySet()){
builder_header.add(key, mapAdd.get(key));
}
}
for (String key:headers_map.keySet()){
builder_header.add(key, headers_map.get(key));
}
Headers headers = builder_header.build();
return headers;
}
public RequestBody getJsonBody(Map<String, String> mapAdd){
/*Json格式的body*/
RequestBody r_body = null;
if (!mapAdd.isEmpty()){
Gson gson = new Gson();
String body_json = gson.toJson(mapAdd);
MediaType postrequestjsontype = MediaType.parse("application/json; charset=utf-8");
r_body = RequestBody.create(postrequestjsontype,body_json);
}
return r_body;
}
public String getBodyParams(Map<String,String> bodyParams) {
//1.添加请求参数
//遍历map中所有参数到builder
if (bodyParams != null && bodyParams.size() > 0) {
StringBuffer stringBuffer = new StringBuffer("?");
for (String key : bodyParams.keySet()) {
if (bodyParams.get(key) != null) {//如果参数不是null就拼接起来
stringBuffer.append("&");
stringBuffer.append(key);
stringBuffer.append("=");
stringBuffer.append(bodyParams.get(key));
}
}
return stringBuffer.toString();
} else {
return "";
}
}
}