返回的JSON我的圖片上傳從Android應用程序服務器和從服務器我送JSON值的響應。從服務器獲取
我怎樣才能獲取JSON在我的應用程序?
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;
}
}
一般當我使用httpClient
我與
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);
沿記錄如果瓦納是程序員,那麼你必須學會如何將一個大問題的小傢伙。喜歡:*從服務器獲取返回的JSON *是:1.請求2.讀取響應(prolly流)3.將流轉換爲字符串。 4.解析字符串作爲JSON ... 1.好像你有它alread ... 2.做互聯網搜索如何獲得與'HttpURLConnection' 3.流響應好像你有這個代碼4.做互聯網搜索... – Selvin
題外話評論:您的副本'fileInputStream'到'dataOutputStream'代碼是可怕的...... – Selvin