android - 我想将 json 发送到我的 API 并接收 Json 形式的响应,但它显示 400 bad request
问题描述
我和使用 google protobuffer 形成我的 json 并作为 post call 发送到服务器但它会返回我 400 Bad Request 但在同一个 json 我将发送给 Postman 它会返回我有效的响应但在 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 调用我从 RegistrationRequestPb 获取 Json
客户服务类
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;
}
}
Http请求
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
{"worker":{"dbInfo":{"id":"ky","lifeTime":"ACTIVE"},"name":{"firstName":"abcd","lastName":"xyz"}, "contactDetails":{"email":{"localPart":"abcd","domain":"gmail.com"},"primaryMobile":{"code":"ISD_91","number":"11734"} ,"secondryMobile":[{"code":"ISD_91","number":"1174"}]},"type":{"personType":"WORKER"},"device":{"macId":" 19:68:15:c4:77:ad","osType":"ANDROID","model":"Redmi","deviceName":"H@cker"}},"login":{"dbInfo": {"id":"k4"},"contactDetails":{"email":{"localPart":"abcd","domain":"gmail.com"},"primaryMobile":{"code":"ISD_91","number":"11734"} ,"secondryMobile":[{"code":"ISD_91","number":"1174"}]},"password":"$2b$12$Wq24XUAyxa6Dyp7RE8ilJ.pYwmRd8uuhvhDWmz6EdEgaY0cFE51TC","personType":{"personType":" WORKER"},"workerRef":{"dbInfo":{"id":"ky"},"name":{"firstName":"abcd","lastName":"xyz"}},"timeCreation": {"日期":"16","月":"10","年":"2019","毫秒":"1571239374500","formattedDate":"2019-10-16 15:22:54","timezone":"IST"}},"status":"SUCCESS"}
解决方案
尝试做这样的事情。
public static String executePost() {
HttpURLConnection connection = null;
InputStream is = null;
try {
//Create connection
URL url = new URL("URL_HERE");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Content-Length", Integer.toString("REQUEST_JSON".getBytes().length));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes("REQUEST_JSON");
wr.close();
//Get Response
try {
is = connection.getInputStream();
} catch (IOException ioe) {
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) connection;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
is = httpConn.getErrorStream();
}
}
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
这会将您的响应作为字符串返回。
推荐阅读
- javascript - 根据时间戳分组日期
- ssis - SSIS 完成包中的所有任务但无法退出包(仍在运行)
- amazon-web-services - 在弹性beantalk中使用Nginx替代apache2
- coldfusion - Coldfusion 会话变量的使用
- html - 将 jQuery 库加载到项目中时,CSS Hamburger 停止工作
- c# - 通过设置 ASPNETCORE_ENVIRONMENT 设置 ASP.NET Core 部署到 azure 获取错误启用开发环境
- javascript - 如何让不和谐的机器人读取另一个机器人的嵌入
- python - Python How to Implement Threading of my Email Class
- r - 如何在我现有的 ggplot2 棒棒糖图表中间插入平均值?
- reactjs - 无法渲染 react-router-dom 基本功能组件