HTTP response code: 403

背景:当用java.net中方法发起网络请求的时,当服务器response回来的信息是“java.io.IOException: Server returned HTTP response code: 403”。可以尝试着在HttpURLConnection对象http中添加请求头“User-Agent”的信息。

403:对请求资源的访问被服务器拒绝(可以通过添加user-agent)(客户端错误)

格式:http.setRequestProperty("User-Agent", "value值");

package com.mark.TestOther;
/**
 * .java.io.IOException: Server returned HTTP response code: 403
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/***
 * 1.构造一个URL对象
 * 2.调用这个这个URL对象的openConnection()--->获得一个URLConnection对象
 * 3.配置URLConnection
 * 4.读取首部信息
 * 5.获得输入流--->读取数据
 * 6.获得输出流--->写入数据
 * 7.关闭连接
 * @author YIMA
 *
 */
public class HttpURLConnectionTest {
    private static String TARGET_URL ="请求的UR";
    private static String user_agent_value="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB7.5; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";

    public static void main(String[] args) throws IOException{
        HttpURLConnectionTest test = new HttpURLConnectionTest();
        System.out.println(test.getResponse());
    }

    private String getResponse() throws IOException {
        URL url = null;
        HttpURLConnection http = null;
        BufferedReader bufferedReader =null;
        InputStream inputStream = null;
        StringBuffer sTotalString = new StringBuffer();
        try{
            //1.构造一个URL对象
            url = new URL(TARGET_URL);

            //2.调用这个这个URL对象的openConnection()
            http = (HttpURLConnection) url.openConnection();

            //3设置请求的方式
            http.setRequestMethod("GET");

            //设置头部的请求参数
            http.setRequestProperty("User-Agent", user_agent_value);

            //5.获得输入流--->读取数据
            inputStream = http.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            // 6.获得输出流--->写入数据
            String sCurrentLine = null;
            while((sCurrentLine = bufferedReader.readLine())!= null){
                sTotalString.append(sCurrentLine);
                sTotalString.append("\r\n");
            }

            return sTotalString.toString();
        }catch(MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            bufferedReader.close();
            inputStream.close();
            http.disconnect();
        }
        return null;
    }
}

你可能感兴趣的:(Java_网络编程)