DefaultHttpClient响应代码400

时间:2013-11-24 14:12:05

标签: java httpclient

http://acm.hdu.edu.cn/showproblem.php/../../../data/images/con208-1004-1.JPG

这是网址,如果你把它复制到浏览器,它运作良好。但是当我使用apache HttpClient下载这个img时。

HttpClient client = new DefaultHttpClient();

我无法下载。我认为这是因为“../”,但在我的程序中,我必须使用这个URL。

1 个答案:

答案 0 :(得分:0)

响应400表示您没有以正确的方式询问httpClient ...

接下来我做了一个简单的尝试:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;



public class  a {

    public static void main(String[] args) throws ClientProtocolException, IOException{

      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet("http://acm.hdu.edu.cn/data/images/con208-1004-1.JPG");
      HttpResponse response = client.execute(request);

      // Get the response
      InputStream inputStream = response.getEntity().getContent();

      OutputStream outputStream = null;

        try {
            // read this file into InputStream 

            // write the inputStream to a FileOutputStream
            outputStream = 
                        new FileOutputStream(new File("C:/test.holder-new.jpg"));

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }

            System.out.println("Done!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }  
}

请注意,不推荐使用DefaultHttpClient。你可以替换它:

HttpClient client = new DefaultHttpClient();

使用:

HttpClient client = HttpClientBuilder.create().build();

这对我有用,请告诉我它是否有帮助。