Ich lade ein Bild von Android App auf Server und als Antwort vom Server sende ich JSON-Werte.Erhalten Sie JSON vom Server
Wie kann ich das JSON in meiner App bekommen?
HttpURLConnection httpURLConnection;
DataOutputStream dataOutputStream;
...
File file = new File(path);
if (file.isFile()) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("http://something.com/upload.php");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
httpURLConnection.setRequestProperty("File", path);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + path + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = httpURLConnection.getResponseCode();
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
}
return true;
}
else {
return false;
}
}
Normalerweise, wenn ich httpClient
verwende ich las es mit
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("utf-8")), 8);
String line;
jsonValue = "";
while ((line = reader.readLine()) != null) {
jsonValue += line;
}
jsonObject = new JSONObject(jsonValue);
Wenn Sie Wana Programmierer sein, dann müssen Sie lernen, wie man ein großes Problem zu kleinen teilen. Wie: * Get zurückgegeben JSON von Server * ist: 1. Anfrage 2. Antwort (Prolly Stream) 3. konvertieren Stream in String. 4. parse string als JSON ... 1. scheint, als ob Sie es schon gehabt hätten ... 2. Suchen Sie im Internet, wie Sie eine Stream-Antwort mit 'HttpURLConnection' erhalten. 3. Es sieht so aus, als hätten Sie diesen Code 4. Suchen Sie im Internet nach ... – Selvin
Off-Topic-Kommentar: Ihre Kopie 'FileInputStream' zu' DataOutputStream' Code ist gruselig ... – Selvin