有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

php在java中将文件(和更多值)发布到http请求中

这是我向url发送HTTP帖子的代码

public static String post(String url, List<BasicNameValuePair> postvalues) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        if ( (postvalues==null) ){
            postvalues= new ArrayList<BasicNameValuePair>();
        } 
        httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        return requestToString(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

我还想在post中添加一个文件(不是一个带有final的byte[],只需将该文件发布到PHP$\u FILES字段中即可

我怎么做

谢谢


共 (1) 个答案

  1. # 1 楼答案

    听起来你想发送一个由多个部分组成的请求。这假设您可以在服务器端处理此类请求:

    HttpParams params = new BasicHttpParams();
    for(BasicNameValuePair postValue: postValues) {
        params.setParameter(postValue.getName(), postValue.getValue());
    }
    
    HttpPost post = new HttpPost();
    post.setParams(params);
    
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(new File(myFile)));
    post.setEntity(entity);
    

    除了将名称-值对作为参数发送外,您还可以像现在一样创建一个UrlEncodedFormEntity实体,并将其作为一个单独的部分添加到多部分实体中