我尝试制作一个带有Camera Bitmap和其他数据的小应用程序,并将它们以Json格式发送到REST API服务器。 到目前为止,我已经编写了下面的代码,但收到错误代码400 Bad request:(
这是在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()
答案 0 :(得分:2)
这是我发送POST的方式
让我知道是否需要任何澄清。
public static String executePost(String targetURL, String requestJSON, String apikey) {
HttpURLConnection connection = null;
InputStream is = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//TODO may be prod or preprod api key
if (apikey.equals(Constants.APIKEY_PREPROD)) {
connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
}
if (apikey.equals(Constants.APIKEY_PROD)){
connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
}
connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
System.out.println(requestJSON);
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(requestJSON);
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();
}
}
}
答案 1 :(得分:0)
这是对我有用的解决方案。从DroiDev提供的解决方案开始,它进行了一些小的更改。
public static String executePost(String targetURL, String requestJSON, String apikey) {
HttpURLConnection connection = null;
InputStream is = null;
String authKey = "Basic " + Base64.encodeToString((apikey + ":").getBytes(), Base64.NO_WRAP);
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", authKey);
connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(requestJSON);
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();
}
}
}