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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值