Я и использую google protobuffer для формирования моего json и отправки в виде почтового звонка на сервер, но он вернет мне 400 плохих запросов, но при этом json, который я отправлю почтальону, вернет мне действительный ответ, но в android это не такотправьте мне действительный ответ, я не понял, что происходит на самом деле
{
"worker": {
"dbInfo": {
"lifeTime": "ACTIVE"
},
"name": {
"firstName": "abc",
"lastName": "xyz"
},
"contactDetails": {
"email": {
"localPart": "abc",
"domain": "gmail.com"
},
"primaryMobile": {
"code": "ISD_91",
"number": "117"
},
"secondryMobile": [
{
"code": "ISD_91",
"number": "117"
}
]
},
"type": {
"personType": "WORKER"
},
"device": {
"macId": "19:68:15:c4:77:ad",
"osType": "ANDROID",
"model": "NOKIA",
"deviceName": "H@cker"
}
},
"password": "new"
}
это мой Json, который отправляет POST-вызов на сервер в коде я получаю Json From RegistrationRequestPb
Класс обслуживания клиентов
public Registration.RegistrationResponsePb getCall(Registration.RegistrationRequestPb request, Class<Registration.RegistrationResponsePb> clazz, Context context, int method) {
HttpCaller caller = new HttpCaller();
try {
return ProtoJsonUtil.fromJson(caller.doCall(request,clazz, UrlPathProvider.UrlPathEnum.REGISTRATION_WORKER,context, RequestMethodEnumAndFormatter.getmethod(RequestMethodEnumAndFormatter.RequestMethodEnum.POST)),clazz);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
HttpCaller
Preconditions.checkArgument(messageOrBuilder != null, messageOrBuilder);
try {
ReqJSON = ProtoJsonUtil.toJson(messageOrBuilder).replaceAll("\\r\\n|\\r|\\n| ", "");
} catch (IOException e) {
e.printStackTrace();
}
URL = m_serverManeger.getServerUrl(data);
OptimusHTTP client = new OptimusHTTP(context);
client.enableDebugging();
ArrayMap<String, String> params = new ArrayMap<>();
params.put("query", ReqJSON);
client.setMethod(method);
client.setMode(OptimusHTTP.MODE_SEQ);
client.setConnectTimeout(10 * 1000);
client.setReadTimeout(10 * 1000);
client.makeRequest(URL, params, new OptimusHTTP.ResponseListener() {
@Override
public void onFailure(String msg) {
Log.e("resperror", msg);
}
@Override
public void onSuccess(String msg) {
Log.e("respsucc", msg);
response = msg;
}
});
return response;
}
OtimusHttp
public interface ResponseListener {
/**
* On failure.
*
* @param msg the msg
*/
void onFailure(String msg);
/**
* On success.
*
* @param msg the msg
*/
void onSuccess(String msg);
}
/**
* The constant METHOD_GET.
*/
public final static int METHOD_GET = 0;
/**
* The constant METHOD_POST.
*/
public final static int METHOD_POST = 1;
/**
* The constant METHOD_PUT.
*/
public final static int METHOD_PUT = 100;
/**
* The constant METHOD_DELETE.
*/
public final static int METHOD_DELETE = 101;
/**
* The constant CONTENT_TYPE_FORM_URL_ENCODED.
*/
public final static String CONTENT_TYPE_FORM_URL_ENCODED = "application/x-www-form-urlencoded";
/**
* The constant CONTENT_TYPE_JSON.
*/
public final static String CONTENT_TYPE_JSON = "application/json";
/**
* The constant CONTENT_TYPE_PDF.
*/
public final static String CONTENT_TYPE_PDF = "application/pdf";
/**
* The constant CONTENT_TYPE_HTML.
*/
public final static String CONTENT_TYPE_HTML = "text/html";
/**
* The constant CONTENT_TYPE_IMG_PNG.
*/
public final static String CONTENT_TYPE_IMG_PNG = "image/png";
/**
* The constant CONTENT_TYPE_TEXT.
*/
public final static String CONTENT_TYPE_TEXT = "text/plain";
/**
* The constant MODE_SEQ.
*/
public final static int MODE_SEQ = 2;
/**
* The constant MODE_PARALLEL.
*/
public final static int MODE_PARALLEL = 3;
private boolean DEBUG = false;
//LOGTAG
private final String LOGTAG = getClass().getSimpleName();
private int connectTimeout = 10 * 1000; //10s
private String contentType = CONTENT_TYPE_JSON;
private Context context;
private ArrayMap<String, String> headerMap = new ArrayMap<>();
private int method;
private int mode;
private int readTimeout = 10 * 1000; //10s
/**
* Instantiates a new Optimus http.
*
* @param context the context
*/
public OptimusHTTP(Context context) {
this.context = context;
setMode(MODE_SEQ);
setMethod(METHOD_GET);
}
/**
* Cancel req.
*
* @param req the req
*/
public void cancelReq(HttpReq req) {
if (req != null && (req.getStatus() == AsyncTask.Status.RUNNING
|| req.getStatus() == AsyncTask.Status.PENDING)) {
req.cancel(true);
if (DEBUG) {
Log.d(LOGTAG, "*---------------------- Request Cancelled ----------------*");
}
}
}
/**
* Enable debugging.
*/
public void enableDebugging() {
DEBUG = true;
}
/**
* Gets connect timeout.
*
* @return the connect timeout
*/
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Sets connect timeout.
*
* @param timeInMs the time in ms
*/
public void setConnectTimeout(int timeInMs) {
this.connectTimeout = timeInMs;
}
/**
* Gets content type.
*
* @return the content type
*/
public String getContentType() {
return contentType;
}
/**
* Sets content type.
*
* @param contentType the content type
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* Gets method.
*
* @return the method
*/
public int getMethod() {
return method;
}
/**
* Sets method.
*
* @param method the method
*/
public void setMethod(int method) {
this.method = method;
}
/**
* Gets mode.
*
* @return the mode
*/
public int getMode() {
return mode;
}
/**
* Sets mode.
*
* @param mode the mode
*/
public void setMode(int mode) {
this.mode = mode;
}
/**
* Gets read timeout.
*
* @return the read timeout
*/
public int getReadTimeout() {
return readTimeout;
}
/**
* Sets read timeout.
*
* @param timeInMs the time in ms
*/
public void setReadTimeout(int timeInMs) {
this.readTimeout = timeInMs;
}
/**
* Make the Request
*
* @param url the url
* @param params the params
* @param listener the listener
* @return HttpReq reference if a request is made null if no request is made
*/
public HttpReq makeRequest(String url, ArrayMap<String, String> params,
ResponseListener listener) {
HttpReq req = new HttpReq(connectTimeout, readTimeout, contentType, headerMap);
HttpReqPkg pkg = new HttpReqPkg();
if (method == METHOD_GET) {
pkg.setMethod("GET");
if (DEBUG) {
Log.e(LOGTAG, "*---------------------- GET Request ----------------------*");
}
} else if (method == METHOD_POST) {
pkg.setMethod("POST");
if (DEBUG) {
Log.e(LOGTAG, "*---------------------- POST Request ----------------------*");
}
} else if (method == METHOD_PUT) {
pkg.setMethod("PUT");
if (DEBUG) {
Log.e(LOGTAG, "*---------------------- PUT Request ----------------------*");
}
} else if (method == METHOD_DELETE) {
pkg.setMethod("DELETE");
if (DEBUG) {
Log.e(LOGTAG, "*---------------------- DELETE Request ----------------------*");
}
}
Log.e("Url",url);
pkg.setUri(url);
pkg.setParams(params);
if (isOnline()) {
if (mode == MODE_SEQ) {
SeqAsyncTask(req, pkg, listener);
} else if (mode == MODE_PARALLEL) {
ParallelAsyncTask(req, pkg, listener);
}
return req;
} else {
if (DEBUG) {
Log.d(LOGTAG, "Not connected to Internet ! OptimusHTTP didn't make a request!");
}
}
return null;
}
public void setHeaderMap(ArrayMap<String, String> headerMap) {
this.headerMap = headerMap;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void ParallelAsyncTask(HttpReq req, HttpReqPkg p, ResponseListener listener) {
req.setOnResultsListener(listener);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
req.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, p);
} else {
req.execute(p);
}
}
private void SeqAsyncTask(HttpReq req, HttpReqPkg p, ResponseListener listener) {
req.setOnResultsListener(listener);
req.execute(p);
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnected();
} else {
return false;
}
}
HttpReq
private int connectTimeout;
private String contentType;
private ArrayMap<String, String> headerMap = new ArrayMap<>();
private OptimusHTTP.ResponseListener listener;
private int readTimeout;
private int resCode;
private String resMsg;
/**
* Instantiates a new Http req.
*
* @param connectTimeout the connect timeout
* @param readTimeout the read timeout
* @param contentType the content type
*/
public HttpReq(int connectTimeout, int readTimeout, String contentType,
ArrayMap<String, String> headerMap) {
resCode = 0;
resMsg = "na";
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.contentType = contentType;
this.headerMap = headerMap;
}
/**
* Sets on results listener.
*
* @param listener the listener
*/
public void setOnResultsListener(OptimusHTTP.ResponseListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(HttpReqPkg... params) {
URL url;
BufferedReader reader = null;
String username = params[0].getUsername();
String password = params[0].getPassword();
String authStringEnc = null;
if (username != null && password != null) {
String authString = username + ":" + password;
byte[] authEncBytes;
authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
authStringEnc = new String(authEncBytes);
}
String uri = params[0].getUri();
if (params[0].getMethod().equals("GET") && params[0].getParams().size()>0) {
uri += "?" + params[0].getEncodedParams();
}
try {
StringBuilder sb;
// create the HttpURLConnection
Log.e("url",uri);
url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (authStringEnc != null) {
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
}
if (params[0].getMethod().equals("POST")
|| params[0].getMethod().equals("PUT")
|| params[0].getMethod().equals("DELETE")) {
// enable writing output to this url
connection.setDoOutput(true);
}
switch (params[0].getMethod()) {
case "POST":
connection.setRequestMethod("POST");
break;
case "GET":
connection.setRequestMethod("GET");
break;
case "PUT":
connection.setRequestMethod("PUT");
break;
case "DELETE":
connection.setRequestMethod("DELETE");
break;
}
// give it x seconds to respond
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept","application/json");
for (int i = 0; i < headerMap.size(); i++) {
connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
}
connection.setRequestProperty("Content-Length",
"" + params[0].getEncodedParams().getBytes().length);
connection.connect();
if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(params[0].getEncodedParams());
writer.flush();
writer.close();
}
// read the output from the server
InputStream in;
resCode = connection.getResponseCode();
resMsg = connection.getResponseMessage();
if (resCode != HttpURLConnection.HTTP_OK) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
reader = new BufferedReader(new InputStreamReader(in));
sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
sb.append(resCode).append(" : ").append(resMsg);
return sb.toString();
} catch (Exception e) {
listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
e.printStackTrace();
} finally {
// close the reader; this can throw an exception too, so
// wrap it in another try/catch block.
if (reader != null) {
try {
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (listener != null && result != null) {
listener.onSuccess(result);
}
}
@Override
protected void onPreExecute() {
disableConnectionReuseIfNecessary();
}
private void disableConnectionReuseIfNecessary() {
// Work around pre-Froyo bugs in HTTP connection reuse.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
HttpPkgReq
private String method = "GET";
private Map<String, String> params = new ArrayMap<>();
private String password = null;
private String uri;
private String username = null;
/**
* Gets encoded params.
*
* @return the encoded params
*/
public String getEncodedParams() {
StringBuilder sb = new StringBuilder();
String value = null;
if(params.size()>0) {
for (String key : params.keySet()) {
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
if(getMethod().equals("GET")) {
sb.append(key).append("=").append(value);
}else{
sb.append(value);
}
}
}
return sb.toString();
}
/**
* Gets method.
*
* @return the method
*/
public String getMethod() {
return method;
}
/**
* Sets method.
*
* @param method the method
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Gets params.
*
* @return the params
*/
public Map<String, String> getParams() {
return params;
}
/**
* Sets params.
*
* @param params the params
*/
public void setParams(Map<String, String> params) {
this.params = params;
}
/**
* Gets uri.
*
* @return the uri
*/
public String getUri() {
return uri;
}
/**
* Sets uri.
*
* @param uri the uri
*/
public void setUri(String uri) {
this.uri = uri;
}
/**
* Gets username.
*
* @return the username
*/
public String getUsername() {
return username;
}
/**
* Sets username.
*
* @param username the username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Sets param.
*
* @param key the key
* @param value the value
*/
public void setParam(String key, String value) {
params.put(key, value);
}
/**
* Gets password.
*
* @return the password
*/
String getPassword() {
return uri;
}
/**
* Sets password.
*
* @param password the password
*/
public void setPassword(String password) {
this.password = password;
}
это мой код, который я использовал для отправки и получения Json, но id отправит мне 400 BAD REQUEST
снимок экрана почтальона, он вернет 200
, пожалуйста, предоставьте мне какое-нибудь решение этого или отправьте какую-нибудь библиотеку, чтобы я использовал их для вызова http-запроса или ответа, используя json
, это мой ответ: с Python Server
{ "рабочий": { "dbInfo": { "ID":»ка " "Lifetime": "ACTIVE"}, "имя": { "Имя": "ABCD", "LastName": "А"}, "contactDetails": { "электронная почта": { "Локальная часть":" ABCD" "домен": "gmail.com"}, "primaryMobile": { "код": "ISD_91", "номер": "11734"}, "secondryMobile": [{ "код": "ISD_91","номер ":" тысяча сто семьдесят четыре "}]}," тип ": {" personType ":" РАБОЧИЙ "}," устройство ": {" MACID ":" 19: 68: 15: с4: 77: объявления», "OSTYPE": "ANDROID", "модель": "редми", "DEVICENAME": "H @ cker"}}, "Войти": { "dbInfo": { "ID": "k4"}, "contactDetails": {»электронная почта ": {" Локальная часть ":" ABCD», "домен": "gmail.com"}, "primaryMobile": { "код": "ISD_91", "номер": "11734"}, "secondryMobile": [{ "код": "ISD_91", "номер": "1174"}]}, "пароль": "$ 2 $ 12 $ Wq24XUAyxa6Dyp7RE8ilJ.pYwmRd8uuhvhDWmz6EdEgaY0cFE51TC", "personType": { "personType": "РАБОТНИК"}, "workerRef": {" dbInfo ": {" ID ":" ка "}," имя ": {" имя ":" ABCD " "LastName": "А"}}, "timeCreation": { "дата":"16 "," month ":" 10 "," year ":" 2019 "," milliseconds ":" 1571239374500 "," formattedDate ":" 2019-10-16 15:22:54 "," timezone ":" IST"}}," статус ":" УСПЕХ "}