2017-04-13 6 views
-1

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); 
+0

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

+0

Off-Topic-Kommentar: Ihre Kopie 'FileInputStream' zu' DataOutputStream' Code ist gruselig ... – Selvin

Antwort

1

Versuchen Sie den folgenden Code unter Verwendung der Reaktion/Fehler aus dem HttpURLConnection

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(); 

      if(serverResponseCode!=200{ 
       //error occurred 
       BufferedReader in=new BufferedReader(new 
         InputStreamReader(
         httpURLConnection.getErrorStream())); 

       StringBuffer sb = new StringBuffer(""); 
       String line=""; 

       while((line = in.readLine()) != null) { 

        sb.append(line); 
        break; 
       } 

       String errorString=sb.toString(); 
      }else{ 
       BufferedReader in=new BufferedReader(new 
         InputStreamReader(
         connection.getInputStream())); 

       StringBuffer sb = new StringBuffer(""); 
       String line=""; 

       while((line = in.readLine()) != null) { 

        sb.append(line); 
        break; 
       } 

       String response=sb.toString(); 
       Log.d(TAG,sb.toString()); 
       in.close(); 
      } 

      fileInputStream.close(); 
      dataOutputStream.flush(); 
      dataOutputStream.close(); 
      //do whatever you wish to do with the error/response string then 

     } 
     return true; 
    } 
    else { 
     return false; 
    } 

jedoch zu lesen, ich Ich rate Ihnen, entweder Volley oder Retrofit als Ihren Http-Client zu verwenden, da sie eine Menge bieten zusätzliche Vorteile gegenüber HttpUrlConnection und AsyncTask. Ich persönlich bevorzuge Retrofit 2, da es mir Tonnen von Vorteilen einschließlich Caching, mehrteiligen Upload/Download, Logging mit schneller Antwort

+0

Hallo. Ich habe Ihren Code ausprobiert, aber 'String response' ist leer. – user3593157

+0

Haben Sie versucht, die Anfrage mit Postman zu replizieren? Sind Sie sicher, dass Sie die Antwort erhalten? –

+0

Ich hatte ein anderes Problem. Jetzt funktioniert es. Vielen Dank! – user3593157

Verwandte Themen