Google Image Upload

MathiasBauer

Bekanntes Mitglied
Hallo zusammen,

ich würde gerne die Funktion von Google "Suche anhand von Bildern" nutzen und ein Bild hochladen. Leider gibt es dafür noch keine API.

Mit folgendem HTML-Code kann man Bilder hochladen:

HTML:
<html>
<head>
</head>
<body>
<form action="http://images.google.com/searchbyimage/upload" enctype="multipart/form-data" method="post">
<input type="file" name="encoded_image">
<input type="hidden" name ="image_content" value="">
<input type="hidden" name ="filename" value="">
<input type="hidden" name ="hl" value="de">
<input type="hidden" name ="sa" value="G">
<input type="hidden" name ="bih" value="373">
<input type="hidden" name ="biw" value="1135">
<input type="hidden" name ="btnG" value="Suchen">
<input type="hidden" name ="image_content" value="">
<input type="submit">
</form>
</body>
</html>

Jetzt ist die Frage, wie kann man das in Java hinbekommen, da redirects mit drinne sind und FollowRedirects(true) nicht funktioniert.

Ich verwende die Libraries von Apache: commons-logging.jar, commons-codec-1.3.jar, commons-httpclient-3.0-rc4.jar

Hier mein Java-Code:
[Java]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;


public class GoogleWrapper {

public String test (String url,String filename) throws IOException{
HttpClient client = new HttpClient();
String response = url;
client.getParams().setParameter("http.useragent", "Test Client");
client.getParams().setParameter("http.connection.timeout",new Integer(5000));

PostMethod method = new PostMethod();
FileOutputStream fos = null;

BufferedReader br = null;

method = new PostMethod(url);
method.addParameter("image_content","");
method.addParameter("filename","");
method.addParameter("hl","de");
method.addParameter("sa","G");
method.addParameter("bih","373");
method.addParameter("biw","1135");
method.addParameter("btnG", "Suchen");

File file = new File(filename);

Part[] parts = {new FilePart("file", file.getName(), file)};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

try{
int returnCode = client.executeMethod(method);

int statuscode = method.getStatusCode();
System.out.println("STATUS CODE = "+statuscode);


if ((statuscode == 301) | (statuscode == 302)) {
// feed has moved
Header location = method.getResponseHeader("Location");
if (!location.getValue().equals("")) {
// recursively check URL until it's not redirected any more
String responseBody = method.getResponseBodyAsString();
System.out.println(responseBody);
String redirectLocation = location.getValue();
System.out.println(redirectLocation);
method = new PostMethod(redirectLocation);
method.setRequestHeader(location);
returnCode = client.executeMethod(method);

statuscode = method.getStatusCode();
System.out.println("STATUS CODE = "+statuscode);
}
} else {
response = url;
}


if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
method.getResponseBodyAsString();

String responseBody = method.getResponseBodyAsString();
System.out.println(responseBody);

} else {
if(returnCode == HttpStatus.SC_OK)
{
String responseBody = method.getResponseBodyAsString();
System.out.println(responseBody);
}
}
} catch (Exception e) {
System.err.println(e);
} finally {
method.releaseConnection();
if(br != null) try { br.close(); } catch (Exception fe) {}
}
return null;
}

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
GoogleWrapper wrapper = new GoogleWrapper();
String filename = "D:/Photos/026.jpg";
wrapper.test("http://images.google.com/searchbyimage/upload",filename);

}

}
[/Java]

Und hier meine Konsolen-Ausgabe:
Code:
14.12.2011 13:54:11 org.apache.commons.httpclient.HttpMethodDirector isRedirectNeeded
INFO: Redirect requested but followRedirects is disabled
STATUS CODE = 302
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://images.google.com/search?tbs=sbi:AMhZZitnglxc3stDxx0TVFeEEdAdEhEfpaASn3s9r0MkYO_1qELcXh35uYPTTkr48gkv7_1IRkDNoB&amp;file=%FF%D8%FF%E1(~Exif">here</A>.
</BODY></HTML>

http://images.google.com/search?tbs=sbi:AMhZZitnglxc3stDxx0TVFeEEdAdEhEfpaASn3s9r0MkYO_1qELcXh35uYPTTkr48gkv7_1IRkDNoB&file=%FF%D8%FF%E1(~Exif
STATUS CODE = 405

Für jeden Ansatz wäre ich dankbar.

Grüße

Mathias
 

AlexSpritze

Bekanntes Mitglied
Am Ende der Konsolen-Ausgabe steht doch als Status Code 405 was "Method Not Allowed" bedeutet. Heißt das, du müsstest anstatt POST GET verwenden? Oder vielleicht PUT?

Oder was passiert, wenn du dem Link in der Ausgabe folgst:
Code:
<A HREF="http://images.google.com/search?tbs=sbi:AMhZZitnglxc3stDxx0TVFeEEdAdEhEfpaASn3s9r0MkYO_1qELcXh35uYPTTkr48gkv7_1IRkDNoB&amp;file=%FF%D8%FF%E1(~Exif">here</A>.
 

MathiasBauer

Bekanntes Mitglied
Vielen Dank für deine Anwort.

Laut Firebug ist es Post. Und der HTML-Code funktioniert auch mit Post.
Hier ein Screenshot aus Firebug:
screenshot.jpg


Wenn ich die Url aus der Konsole aufrufe, sagt mir das, dass das Bild nicht upgeloaded wurde.


Verwende ich MultipartRequestEntity richtig?


Wird ein Bild wirklich so gesendet und der PostMethod mit angehängt?
 

MathiasBauer

Bekanntes Mitglied
Ich glaube, dass es an diesen Zeilen liegt:

Java:
PostMethod method  = new PostMethod();
File file = new File(filename);
Part[] parts = {new FilePart("file", file.getName(), file)};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

Kann ich auf diese Weise per PostMethod Dateien versenden? Fehlt noch etwas?
 

MathiasBauer

Bekanntes Mitglied
Ich bin etwas weiter gekommen:
Nach der PostMethod folgt eine GetMethod.

Allerdings ist nur bei der PostMethod der Status 302. Bei der GetMethod bekomme ich den Status 200 zurück.

Laut Firebug werden aber 7 Get-Anfragen gesendet.

Bei der ersten Weiterleitung (nach der PostMethod) sieht die Url in etwa so aus:
http://images.google.com/search?tbs=sbi:AMhZZisQr_1XYfQPfzgrp7SyWR7trwG8dvPWi8Q0IKOZmcmI_196cHyVdrfqIdN9ZhBicqqK6MxUkl&file=%FF%D8%FF%E1

Von der GetMethod bekomme ich allerdings keinen Header, da der Status 200 ist.

Wie komme ich an den Referer?
(z.B. GoogleUrl)
 

areafo

Mitglied
Getting Started - Google Image Search API - Google Code

werfe ich mal so in den raum. das ganze (api) ist als deprecated gekennzeichnet. wahrscheinlich wäre eine automatisierung wie du sie vorhast ein verstoß?


Using Java
The following code snippet shows how to make a request to the Google Image Search API using Java. This example uses the JSON library from json.org.
Java:
URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
                  "v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", /* Enter the URL of your site here */);

String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
 builder.append(line);
}

JSONObject json = new JSONObject(builder.toString());
// now have some fun with the results...
 

MathiasBauer

Bekanntes Mitglied
Danke für deine Antwort.

Jedoch gibt es leider keine API von Google, um Bilder für die Bildersuche hochzuladen. Andersherum geht es schon. Zuerst kann man nach einem Suchbegriff suchen und dann die Bilder runterladen.
 

MathiasBauer

Bekanntes Mitglied
Leider bin ich nicht weitergekommen. Mein Prof hat mich von der Aufgabe erlöst, da wir im Praktikum einen anderen Schwerpunkt hatten.

Den Inhalt des Links kenne. Das war auch meine Grundlage. Allerdings hat es nicht zum Erfolg geführt.

Ich habe es auch nochmal in PHP versucht. Hier der Forumsbeitrag:
Google Image Upload - php.de

Dort wurde ich u.a. daruaf hingewiesen, dass es nicht erlaubt ist, außerhalb der APIs automatisiert Suchanfragen zu stellen.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
M com.google.gson wird nicht erkannt Netzwerkprogrammierung 2
J Google Drive Netzwerkprogrammierung 2
S HTTP Download von Google-URL mit Parametern Netzwerkprogrammierung 1
T GWT mit Google App Engine Netzwerkprogrammierung 0
Y HTTP Google Reader API Kommunikation Netzwerkprogrammierung 3
Dit_ UDP Port testen | Ping Google? Netzwerkprogrammierung 7
M Google Translate über Java ansprechen? Netzwerkprogrammierung 13
L Google Suchergebnisse in Java Applikation Netzwerkprogrammierung 4
S Google Search Webservice mit Apache Axis realisieren? Netzwerkprogrammierung 2
P URL - 403 ERROR - Google News - PHP geht Netzwerkprogrammierung 5
G Google-Suche funktioniert nicht Netzwerkprogrammierung 6
B google durchsuchen mit URL.openStream() Netzwerkprogrammierung 5
bummerland Google liefert HTTP response code 403 Netzwerkprogrammierung 2
M PdfPCell, Image und Chunk Netzwerkprogrammierung 4
S Server-Client: Image senden Netzwerkprogrammierung 2
T SWT Image versenden Netzwerkprogrammierung 2
T Image aus Applet an PHP Seite senden? Netzwerkprogrammierung 3
U Image erzeugen aus empfangenen Daten Netzwerkprogrammierung 7
N java.awt.image.BufferedImage über Socket schicken Netzwerkprogrammierung 3
J FTP Upload über Proxy funktioniert nicht Netzwerkprogrammierung 1
D CSV File Upload Netzwerkprogrammierung 5
P nanoHttp upload.html page lädt nicht Netzwerkprogrammierung 4
M HTTP File Upload mit Prozessbar Funktioniert nicht. Netzwerkprogrammierung 8
5 File Upload/ ClassNotFoundException Netzwerkprogrammierung 9
B FTPS Upload Netzwerkprogrammierung 3
M Apache Solr doc & pdf Upload Netzwerkprogrammierung 8
C apache commons net ftp bei upload unvollständig Netzwerkprogrammierung 3
C HTTP Mediawiki Upload Netzwerkprogrammierung 9
D FTP Pfadangabe für ftp-upload funktioniert nicht Netzwerkprogrammierung 5
R HTTP HttpURLConnection Large File Upload Netzwerkprogrammierung 1
1 Upload problem! org.apache.commons.net.ftp Netzwerkprogrammierung 3
E Applet zum Datei-Upload Netzwerkprogrammierung 3
P Bilder: FTP-Upload funktioniert nicht richtig Netzwerkprogrammierung 2
W HTTP-Upload Netzwerkprogrammierung 2
K Datei-Upload per FTP Netzwerkprogrammierung 2
E Upload großer Dateien? Netzwerkprogrammierung 5
E upload progress bei einem http file post Netzwerkprogrammierung 5
eskimo328 progress bar mit upload speed Netzwerkprogrammierung 19
J Java Programm für Upload von Dateien per HTTP Netzwerkprogrammierung 7
L file upload / download über http Netzwerkprogrammierung 5
J File upload mit ftp Netzwerkprogrammierung 4

Ähnliche Java Themen

Neue Themen


Oben