28

我需要将一些数据上传到 PHP 服务器。我可以使用参数发布:

String url = "http://yourserver";

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpClient.execute(httpPost);
}

我还可以上传文件:

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...
}

但是我怎么能把它放在一起呢?我需要在一篇文章中上传图片和参数。谢谢

4

5 回答 5

13

您必须使用 MultipartEntity。在线查找并下载这两个库:httpmime-4.0.jarapache-mime4j-0.4.jar,然后您可以根据需要附加任意数量的内容。以下是如何使用它的示例:

HttpPost httpost = new HttpPost("URL_WHERE_TO_UPLOAD");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myString", new StringBody("STRING_VALUE"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);

对于服务器端,您可以使用这些实体标识符名称myImageFile和.myStringmyAudioFile

于 2012-10-21T22:21:40.810 回答
11

您必须使用多部分 http 帖子,就像在 HTML 表单中一样。这可以通过一个额外的库来完成。有关完整示例,请参阅使用 Http Post 发送图像一文。

于 2012-10-21T22:22:31.613 回答
4

这对我来说就像魅力:

public int uploadFile(String sourceFileUri) {  

    String fileName=sourceFileUri;
    HttpURLConnection conn = null;
    DataOutputStream dos = null;  
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "------hellojosh";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(fileName); 
    Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);

    if (!sourceFile.isFile()) {                                
         Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);                
         runOnUiThread(new Runnable() {
            public void run() {             
                //messageText.setText("Source File not exist :"
                }
            });          
         return 0;  //RETURN #1
         }
    else{
        try{                

             FileInputStream fileInputStream = new FileInputStream(sourceFile);           
             URL url = new URL(upLoadServerUri);
             Log.v("joshtag",url.toString());

             // Open a HTTP  connection to  the URL
             conn = (HttpURLConnection) url.openConnection(); 
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy            s       
             conn.setRequestMethod("POST");                     
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);     
             conn.setRequestProperty("file", fileName);                     
             conn.setRequestProperty("user", user_id));

             dos = new DataOutputStream(conn.getOutputStream());  
             //ADD Some -F Form parameters, helping method
             //... is declared down below
             addFormField(dos, "someParameter", "someValue");

             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);                    
             dos.writeBytes(lineEnd);      

             // create a buffer of  maximum size
             bytesAvailable = fileInputStream.available();           
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];         
             // read file and write it into form...
             bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

             while (bytesRead > 0) {                        
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    Log.i("joshtag","->");
                    }

             // send multipart form data necesssary after file data...
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

             // Responses from the server (code and message)
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage().toString();              
             Log.i("joshtag", "HTTP Response is : "  + serverResponseMessage + ": " + serverResponseCode);  

             // ------------------ read the SERVER RESPONSE
             DataInputStream inStream;
             try {
                 inStream = new DataInputStream(conn.getInputStream());
                 String str;
                 while ((str = inStream.readLine()) != null) {
                     Log.e("joshtag", "SOF Server Response" + str);
                    }
                 inStream.close();
                }
             catch (IOException ioex) {
                Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
                }

             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();    

             if(serverResponseCode == 200){ 
                //Do something                       
                }//END IF Response code 200  

            dialog.dismiss();
            }//END TRY - FILE READ      
        catch (MalformedURLException ex) {
            ex.printStackTrace();     
            Log.e("joshtag", "UL error: " + ex.getMessage(), ex);  
            } //CATCH - URL Exception

         catch (Exception e) {           
            e.printStackTrace();             
            Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
            } //

        return serverResponseCode; //after try       
        }//END ELSE, if file exists.
    }


public static String lineEnd = "\r\n";
public static String twoHyphens = "--";
public static String boundary = "------------------------afb19f4aeefb356c";
public static void addFormField(DataOutputStream dos, String parameter, String value){
    try {
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\""+parameter+"\"" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(value);
        dos.writeBytes(lineEnd);
    }
    catch(Exception e){

    }
}

更新:如果您需要与文件一起发送参数,请使用:

conn.setRequestProperty("someParameter","someValue")
//or
addFormField(DataOutputStream dos, String parameter, String value)

...如上面的代码所示。如果您不完全了解您尝试连接的服务器,则其中一个应该可以工作。

于 2015-12-30T10:23:21.787 回答
1

当心

MultiPartEntity并且BasicNameValuePair弃用

所以这是新的方法!您只需httpcore.jar(latest)要从httpmime.jar(latest)Apache站点下载它们。

try
{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    entityBuilder.addTextBody(USER_ID, userId);
    entityBuilder.addTextBody(NAME, name);
    entityBuilder.addTextBody(TYPE, type);
    entityBuilder.addTextBody(COMMENT, comment);
    entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
    entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));

    if(file != null)
    {
        entityBuilder.addBinaryBody(IMAGE, file);
    }

    HttpEntity entity = entityBuilder.build();
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    result = EntityUtils.toString(httpEntity);
    Log.v("result", result);
}
catch(Exception e)
{
    e.printStackTrace();
}
于 2015-11-27T21:44:51.510 回答
0

使用这个异步任务。

    class httpUploader2 extends AsyncTask<Void, Void, Void> {
    private final static String boundary =  "*****M9J_cfALt*****";
    private final static String multiPartFormData = "multipart/form-data;boundary=" + boundary;
    @Override
    protected Void doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://192.168.43.20/test.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Cache-Control", "no-cache");
            urlConnection.setRequestProperty("Content-Type", multiPartFormData);
            urlConnection.setUseCaches( false );
            urlConnection.setChunkedStreamingMode(0);

            DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
            writeField(request,"hellow","world");
            writeFile(request,"file1","testfilename.txt","this is file content as string".getBytes(StandardCharsets.UTF_8));
            writeField(request,"testtt","valueeee");
            writeFile(request,"file2","testfilename2222.txt","this is file content as string".getBytes(StandardCharsets.UTF_8));
            request.flush();
            request.close();

            int code = urlConnection.getResponseCode();
            if (code ==  HTTP_OK) {
                //Log.d("@#$","Connected");
                BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    Log.i("@#$", line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return null;
    }
    private void writeField(DataOutputStream request,String name,String value){
        String out = "\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name +"\"";
        out += "\r\n\r\n" + value;
        try {
            request.write(out.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ignored) {}
    }
    private void writeFile(DataOutputStream request,String name,String value,byte[] filedata){
        String out = "\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name +"\"; filename=\"" + value + "\"";
        out += "\r\n\r\n";
        try {
            request.write(out.getBytes(StandardCharsets.UTF_8));
            request.write(filedata);
        } catch (IOException ignored) {}
    }
}

使用这个 php 进行测试(test.php) -

<?php
var_dump($_REQUEST);
echo "--------UPLOADED FILES--------\n";
var_dump($_FILES);
?>

我在真实测试设备上使用 Android Pie,所以需要在清单中声明,否则无法连接-

<application
        android:usesCleartextTraffic="true"
.
.
/></application>

使用 xampp 测试 php 服务器。但您不能直接在手机上访问它(真正的测试设备)。为此,首先将您的 PC 连接到设备热点。然后在 apache 的 httpd.txt 中添加 Require all grant。

然后要获取该热点网络的 xampp 的 IP 地址,请编写 ipconfig 并查找 ipv4 地址。

于 2020-08-30T09:32:58.097 回答