Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java HTTP POST连接发送图像文件_Java_Http_Post_Upload - Fatal编程技术网

使用java HTTP POST连接发送图像文件

使用java HTTP POST连接发送图像文件,java,http,post,upload,Java,Http,Post,Upload,我正在尝试使用JavaHTTPPOST请求向网站发送图像 我使用的是这里使用的基本代码: 这是我的修改: String urlToConnect = "http://localhost:9000/upload"; File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just gen

我正在尝试使用JavaHTTPPOST请求向网站发送图像

我使用的是这里使用的基本代码:

这是我的修改:

String urlToConnect = "http://localhost:9000/upload";
File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.

URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
    writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
    writer.println("--" + boundary);
    writer.println("Content-Disposition: form-data; name=\"picture\"; filename=\"bla.jpg\"");
    writer.println("Content-Type: image/jpeg");
    writer.println();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload)));
        for (String line; (line = reader.readLine()) != null;) {
            writer.println(line);
        }
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    }
    writer.println("--" + boundary + "--");
} finally {
    if (writer != null) writer.close();
}

// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
我最终得到了200个响应码,但图像有缺陷,比如随机颜色,这让我认为这是字符编码中的错误。我尝试使用UTF-8作为原始示例,但这只会创建一个损坏的映像

我也100%确定这不是服务器端问题,因为我可以使用诸如高级rest客户端/邮递员之类的rest客户端,它们可以毫无问题地发送映像

你能帮我找出毛病吗?多谢各位

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9000/upload");
    File file = new File("C:\\Users\\joao\\Pictures\\bla.jpg"");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

用于计算此代码。最好使用稳定的库,而不是从头开始处理,除非有需要以自定义方式处理的内容。

Reader/Writer类用于处理文本数据,而图像是二进制的。您需要将文件解释为二进制文件:

FileChannel         in  = new FileInputStream(fileToUpload).getChannel();
WritableByteChannel out = Channels.newChannel(connection.getOutputStream());

in.transferTo(0, fileToUpload.size(), out)
当然,您仍然需要关闭所有打开的资源

试试看:

private DefaultHttpClient mHttpClient;
Context context;
public String error = "";

//Contrutor para que metodos possam ser usados fora de uma activity
public HTTPconector(Context context) {
    this.context = context;
}


public HTTPconector() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);
}


public void FileClientPost(String txtUrl, File file){
    try
    {
        error = "";
        HttpPost httppost = new HttpPost(txtUrl);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("Image", new FileBody(file));
        httppost.setEntity(multipartEntity);
        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
    }
    catch (Exception e)
    {
        Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e);
        e.getStackTrace();
        error = e.getMessage();
    }
}

//Verifica se a rede esta disponível
public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

public String Get(String txtUrl){
    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setReadTimeout(10000);
        con.setConnectTimeout(15000);
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.connect();

        return readStream(con.getInputStream());

    }  catch (ProtocolException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    }
}


public String Post(String txtUrl){
    File image;

    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();

        //con.getOutputStream().write( ("name=" + "aa").getBytes());

        return readStream(con.getInputStream());
    } catch (ProtocolException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    }
}


//Usado para fazer conexão com a internet
public String conectar(String u){
    String resultServer = "";
    try {
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        resultServer = readStream(con.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        resultServer = "ERRO: "+ e.getMessage();
    }

    Log.i("HTTPMANAGER: ", resultServer);
    return resultServer;
}

//Lê o resultado da conexão
private String readStream(InputStream in) {
    String serverResult = "";
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        serverResult = reader.toString();
    }   catch (IOException e) {
        e.printStackTrace();
        serverResult = "ERRO: "+ e.getMessage();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                serverResult = "ERRO: "+ e.getMessage();
            }
        }
    }
    return  serverResult;
}

private class PhotoUploadResponseHandler implements ResponseHandler<Object>
{
    @Override
    public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException {

        HttpEntity r_entity = response.getEntity();
        String responseString = EntityUtils.toString(r_entity);
        Log.d("UPLOAD", responseString);
        return null;
    }
}
私有默认HttpClient mHttpClient;
语境;
公共字符串错误=”;
//承包商应为本项目的活动承担责任
公共HttpConctor(上下文){
this.context=上下文;
}
公共HTTPconector(){
HttpParams params=新的BasicHttpParams();
setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
mHttpClient=新的DefaultHttpClient(参数);
}
public void FileClientPost(字符串txtUrl,文件){
尝试
{
错误=”;
HttpPost HttpPost=新的HttpPost(txtUrl);
MultipartEntity MultipartEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
addPart(“图像”,新的文件体(文件));
httppost.setEntity(多协议实体);
执行(httppost,newphotouploadresponsehandler());
}
捕获(例外e)
{
e(HTTPconector.class.getName(),e.getLocalizedMessage(),e);
e、 getStackTrace();
错误=e.getMessage();
}
}
//验证是否重新设置显示级别
公共布尔值isNetworkAvailable(){
ConnectivityManager cm=(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=cm.getActiveNetworkInfo();
//如果没有可用的网络,networkInfo将为空
//否则,请检查我们是否连接
if(networkInfo!=null&&networkInfo.isConnected()){
返回true;
}
返回false;
}
公共字符串Get(字符串txtUrl){
试一试{
URL=新的URL(txtrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setReadTimeout(10000);
con.设置连接超时(15000);
con.setRequestMethod(“GET”);
con.setDoInput(真);
con.connect();
返回readStream(con.getInputStream());
}捕获(协议例外e){
e、 printStackTrace();
返回“ERRO:+e.getMessage();
}捕获(IOE异常){
e、 printStackTrace();
返回“ERRO:+e.getMessage();
}
}
公共字符串Post(字符串txtUrl){
文件图像;
试一试{
URL=新的URL(txtrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod(“POST”);
con.setDoInput(真);
con.设置输出(真);
con.connect();
//con.getOutputStream();
返回readStream(con.getInputStream());
}捕获(协议例外e){
e、 printStackTrace();
返回“ERRO:+e.getMessage();
}捕获(IOE异常){
e、 printStackTrace();
返回“ERRO:+e.getMessage();
}
}
//Usado para fazer conexão com互联网
公共字符串连接符(字符串u){
字符串resultServer=“”;
试一试{
URL=新URL(u);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
resultServer=readStream(con.getInputStream());
}捕获(例外e){
e、 printStackTrace();
resultServer=“ERRO:+e.getMessage();
}
Log.i(“HTTPMANAGER:,resultServer”);
返回结果服务器;
}
//莱奥·雷斯塔多·达·科内克斯昂(Lêo resultado da conexão)
私有字符串读取流(输入流输入){
字符串serverResult=“”;
BufferedReader reader=null;
试一试{
reader=新的BufferedReader(新的InputStreamReader(in));
字符串行=”;
而((line=reader.readLine())!=null){
系统输出打印项次(行);
}
serverResult=reader.toString();
}捕获(IOE异常){
e、 printStackTrace();
serverResult=“ERRO:+e.getMessage();
}最后{
if(读卡器!=null){
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
serverResult=“ERRO:+e.getMessage();
}
}
}
返回服务器结果;
}
私有类PhotoUploadResponseHandler实现ResponseHandler
{
@凌驾
公共对象HandlerResponse(HttpResponse响应)抛出ClientProtocolException,IOException{
HttpEntity r_entity=response.getEntity();
字符串responseString=EntityUtils.toString(r\u实体);
Log.d(“上传”,响应预算);
返回null;
}
}

今天我遇到了同样的问题,我写了一个小服务器,它只支持两条路径,上传和下载图像

客户机应该是一个java类,它通过标准向服务器发送图像负载

如果你想知道原因,请从这篇文章中查看Ciro Santilli的答案:

幸运的是,我发现了这个非常好的示例代码:

它展示了我们如何在没有任何外部库的情况下手动构建多部分http主体的有效负载,从我的角度来看,唯一的限制是,它只处理一个文件的多部分主体


因为我没有HTML页面来嗅探生成的POST负载,
import requests
posturl = 'http://<server>:<port>/<path>'
files = {'image' : open('<file>', 'rb')}
r = requests.post(posturl, files = files)
HttpURLConnection conn =
        (HttpURLConnection) new URL("http://<server>:<port>/<path>")).openConnection();

// some arbitrary text for multitext boundary
// only 7-bit US-ASCII digits max length 70
String boundary_string = "some radom/arbitrary text";

// we want to write out
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary_string);

// now we write out the multipart to the body
OutputStream conn_out = conn.getOutputStream();
BufferedWriter conn_out_writer = new BufferedWriter(new OutputStreamWriter(conn_out));
// write out multitext body based on w3 standard
// https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
conn_out_writer.write("\r\n--" + boundary_string + "\r\n");
conn_out_writer.write("Content-Disposition: form-data; " +
        "name=\"image\"; " +
        "filename=\""+ <File class instance>.getName() +"\"" +
        "\r\n\r\n");
conn_out_writer.flush();

// payload from the file
FileInputStream file_stream = new FileInputStream(<File class instance>);
// write direct to outputstream instance, because we write now bytes and not strings
int read_bytes;
byte[] buffer = new byte[1024];
while((read_bytes = file_stream.read(buffer)) != -1) {
conn_out.write(buffer, 0, read_bytes);
}
conn_out.flush();
// close multipart body
conn_out_writer.write("\r\n--" + boundary_string + "--\r\n");
conn_out_writer.flush();

// close all the streams
conn_out_writer.close();
conn_out.close();
file_stream.close();
// execute and get response code
conn.getResponseCode();