使用JAva执行浏览器的URL后获取响应

时间:2017-03-19 22:54:42

标签: java http

我是Java和Http请求的新手。我在执行URL后尝试获取响应。情况就是这样: 我有这个网址:

https://api.instagram.com/oauth/authorize/?client_id=63092ass123&redirect_uri=http%3A%2F%2Fexample.com%2F&response_type=code&scope=basic

并在浏览器中执行后,它会使用重定向链接进行响应,如:

http://example.com/?code=abcd123

我想要做的是自动化流程并获取响应代码(abc123)。 我一直在阅读有关httpclient的内容,并按照[教程] [1]进行了阅读,但这就是我得到的内容:

HTTP/1.1 200 OK
org.apache.http.client.entity.DecompressingEntity@1e9e725a
HTTP/1.1 302 Found
[Content-Type: text/html; charset=utf-8,Content-Length: 0,Chunked: false]

我想我没有得到正确的方法,对吗?

修改 我已经按照每个教程和每个回复,但正如我所提到的,我是新手,我找不到这样做的方法。这就是我实际上正在做的事情,我不知道为什么不能得到代码:

public static String clientid = "5348f1b98f60418995eb9830297dffe0";
public static String secretcli = "aa541c5013eb4ca2a93d92b46d3c0e4a";
public static String BackUri = "http://aieduca.com/";
  public static void main(String[] args) throws ClientProtocolException, IOException  {
    InstagramService service = new InstagramAuthService()
                .apiKey(clientid)
                .apiSecret(secretcli)
                .callback("http://aieduca.com/")     
                .scope("basic")
                .build();

      String authorizationUrl = service.getAuthorizationUrl();
      System.out.println("Autoriz= "+authorizationUrl);


      try {

          URLConnection con = new URL( authorizationUrl ).openConnection();
          System.out.println( "orignal url: " + con.getURL() );
          con.connect();
          System.out.println( "connected url: " + con.getURL() );
          InputStream is = con.getInputStream();
          //url2=con.toString();
          System.out.println( "redirected url: " + con.getURL() );            

          HttpURLConnection con1 = (HttpURLConnection)(new URL( authorizationUrl ).openConnection());
          con1.setInstanceFollowRedirects( false );
          con1.connect();
          int responseCode = con1.getResponseCode();
          System.out.println( "ResFinal: "+responseCode );
          String location = con1.getHeaderField( "Location" );
          System.out.println( location );

          HttpURLConnection con2 = (HttpURLConnection)(new URL( location ).openConnection());
          con2.connect();
          System.out.println( "connected url1: " + con2.getURL() );
          InputStream is1 = con2.getInputStream();
          System.out.println( "redirected url1: " + con2.getURL() );

          is.close();
        } finally {
            System.out.println("END.");

我很沮丧所以如果有同样问题的人能帮到我,我会非常感激。

1 个答案:

答案 0 :(得分:0)

您可以在构建HttpClient时设置RedirectStrategy,从而禁用自动重定向。看一下这个例子:https://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.html#d5e334