Я пытаюсь создать небольшое приложение, которое принимает растровое изображение камеры и другие данные и отправляет их на сервер API REST в формате Json.
Пока что я написал код ниже, но я получаю код ошибки 400 Плохой запрос: (
Это в MainActivity
private void SendPictureToServer(String sPhoto) {
try {
String baseUrl = "http://192.168.0.1:7100/api/v1/save/img";
String username = "52363cc0cb3a442ebc98ba399f47ca3d"; // <= api key
String password = "";
JSONObject postData = new JSONObject();
postData.put("pl", "1");
postData.put("id", "76885");
postData.put("name", "photo");
postData.put("ext", "jpg");
postData.put("type", "Product picture #1");
postData.put("img", sPhoto);
ApiClient apiClient = new ApiClient(baseUrl, username, password);
AsyncTask<Void, Void, String> execute = new ExecuteNetworkOperation(apiClient, postData.toString(), "POST");
execute.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
Это также в MainActivity
public class ExecuteNetworkOperation extends AsyncTask<Void, Void, String> {
private ApiClient apiClient;
private String isValidCredentials = "";
private String postData = "";
private String httpMethod = "";
public ExecuteNetworkOperation(ApiClient apiClient, String postData, String httpMethod) {
this.apiClient = apiClient;
this.postData = postData;
this.httpMethod = httpMethod;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// Display the progress bar.
// findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Void... params) {
try {
if (httpMethod == "POST" && !TextUtils.isEmpty(postData))
{
apiClient.setHttpMethod("POST");
isValidCredentials = apiClient.executePostData(postData);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Hide the progress bar.
//findViewById(R.id.loadingPanel).setVisibility(View.GONE);
if (isValidCredentials.equals("true")) {
Toast.makeText(getApplicationContext(), "Successful connection", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_LONG).show();
}
}
}
А это в ApiClient.java
public class ApiClient {
private String baseUrl;
private String username;
private String password;
private String urlResource;
private String urlPath;
private String lastResponse;
private String payload;
private String httpMethod;
private HashMap<String, String> parameters;
private Map<String, List<String>> headerFields;
public ApiClient(String baseUrl, String username, String password) {
setBaseUrl(baseUrl);
this.username = username;
this.password = password;
this.urlResource = "";
this.urlPath = "";
this.httpMethod = "";
parameters = new HashMap<>();
lastResponse = "";
payload = "";
headerFields = new HashMap<>();
// This is important. The application may break without this line.
System.setProperty("jsse.enableSNIExtension", "false");
}
public ApiClient setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
if (!baseUrl.substring(baseUrl.length() - 1).equals("/")) {
this.baseUrl += "/";
}
return this;
}
public ApiClient setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public ApiClient clearAll() {
parameters.clear();
baseUrl = "";
this.username = "";
this.password = "";
this.urlResource = "";
this.urlPath = "";
this.httpMethod = "";
lastResponse = "";
payload = "";
headerFields.clear();
return this;
}
public String executePostData(String postJsonData) {
StringBuilder outputStringBuilder = new StringBuilder();
try {
String userCredentials = new String(username + ":" + password);
String basicAuth = "Basic " + Base64.encodeToString(userCredentials.getBytes(), Base64.NO_WRAP);
URL url = new URL(this.baseUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty ("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setConnectTimeout(10000);
try {
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(postJsonData);
writer.flush();
writer.close();
outputStream.close();
headerFields = connection.getHeaderFields();
int responseCode = connection.getResponseCode();
String responseMess = connection.getResponseMessage();
InputStream errorStream = connection.getErrorStream();
Log.e("postJsonData ", postJsonData);
Log.e("headerFields ", headerFields.toString());
Log.e("ResponseCod ", String.valueOf(responseCode));
Log.e("ResponseMessage ", responseMess);
Log.e("ErrorStream ", errorStream.toString());
if (responseCode == HttpURLConnection.HTTP_OK) {
outputStringBuilder.append("true : ");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
outputStringBuilder.append(line);
}
bufferedReader.close();
}else {
outputStringBuilder.append(new String("false : "+responseCode +" " + responseMess + " " + errorStream.toString()));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return outputStringBuilder.toString();
}
}
Это из Logcat
07-03 18:32:19.427 30515-31533 E/headerFields: {null=[HTTP/1.1 400 Bad Request], Content-Length=[0], Date=[Tue, 03 Jul 2018 15:31:07 GMT], Server=[Microsoft-HTTPAPI/2.0], X-Android-Received-Millis=[1530631939426], X-Android-Response-Source=[NETWORK 400], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1530631939299]}
07-03 18:32:19.427 30515-31533 E/ResponseCod: 400
07-03 18:32:19.428 30515-31533 E/ResponseMessage: Bad Request
07-03 18:32:19.428 30515-31533 E/ErrorStream: buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()
07-03 18:32:19.428 30515-30515 E/isValidCredentials: false : 400 Bad Request buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()