2012-01-21 10 views
4

イメージをPHPページにアップロードしようとしています。そのため、PHPページはその処理方法を知っています。現在、私はこれを使用して、それを離れて取得しています:Android:他のPOST文字列と一緒にページにファイルをアップロードする

URL url = new URL("http://www.tagverse.us/upload.php?authcode="+WEB_ACCESS_CODE+"&description="+description+"&userid="+userId); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setDoOutput(true); 
connection.setRequestMethod("POST"); 

OutputStream os = connection.getOutputStream(); 
InputStream is = mContext.getContentResolver().openInputStream(uri); 
BufferedInputStream bis = new BufferedInputStream(is); 
int totalBytes = bis.available(); 

for(int i = 0; i < totalBytes; i++) { 
    os.write(bis.read()); 
} 
os.close(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
String serverResponse = ""; 
String response = ""; 

while((response = reader.readLine()) != null) { 
    serverResponse = serverResponse + response; 
} 
reader.close(); 
bis.close(); 

は、GET/POSTハイブリッドを持つほか、これによりエレガントな解決策はありますか?まるでこれがぎこちないように感じますが、私が知る限り、それは完全に容認できる解決策です。これを行うより良い方法があれば、私は正しい方向を指していることを感謝します。ありがとう!

PS:私はあなたが、通常の条件下では、POSTを経由してPHPページと相互作用する方法に精通しています:

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://www.tagverse.us/login.php"); 

try { 
    List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
    pairs.add(new BasicNameValuePair("authcode", WEB_ACCESS_CODE)); 
    pairs.add(new BasicNameValuePair("username", username)); 
    pairs.add(new BasicNameValuePair("password", password)); 
    post.setEntity(new UrlEncodedFormEntity(pairs)); 
    client.execute(post); 
} 

基本的に私は何をしたいのですがこれらの2つの方法を組み合わせているが、理由はI HttpPostオブジェクトではなくHttpURLConnectionオブジェクトで動作しますが、2つをマージするだけでは簡単ではありません。

ありがとうございました!あなたは、私がこれと同様の問題のために追加の回答を見てみ試すことができます

答えて

1

:ここ https://stackoverflow.com/a/9003674/472747

は、コードは次のとおりです。

byte[] data = {10,10,10,10,10}; // better get this from a file or memory 
HttpClient httpClient = new DefaultHttpClient(); 
HttpPost postRequest = new HttpPost("server url"); 
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg"); 
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
reqEntity.addPart("image", bab); 

FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue")); 
reqEntity.addPart(bodyPart); 
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2")); 
reqEntity.addPart(bodyPart); 
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3")); 
reqEntity.addPart(bodyPart); 
postRequest.setEntity(reqEntity); 
HttpResponse response = httpClient.execute(postRequest); 
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
String line = null; 
while((line = in.readLine()) != null) { 
    System.out.println(line); 
} 
関連する問題