Java Code Examples for java.net.HttpURLConnection.getHeaderFields()

The following are Jave code examples for showing how to use getHeaderFields() of the java.net.HttpURLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: NEILREN4J   File: PhilisenseKaoQinService.java   Source Code and License Vote up 6 votes
/**
 * 登陆获取 Cookie
 *
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private String postLogin(String username, String password) throws Exception {
    String meCookie = null;//(String) memcachedManager.get("PLX_" + username + "_" + password);
    if (meCookie != null && !meCookie.equals("")) {
        this.Cookie = meCookie;
        return meCookie;
    }
    URL url = new URL(PLX + "/WebRoot/LoginAction.do");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);

    con.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded; text/html; charset=UTF-8");
    con.setConnectTimeout(1000);
    con.setReadTimeout(3000);
    OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
    osw.write("activity=login&userId=" + username + "&password=" + password);
    osw.flush();
    osw.close();
    /////////////
    //从请求中获取cookie列表
    String cookieskey = "Set-Cookie";
    Map<String, List<String>> maps = con.getHeaderFields();
    List<String> coolist = maps.get(cookieskey);
    Iterator<String> it = coolist.iterator();
    StringBuffer sbu = new StringBuffer();
    while (it.hasNext()) {
        sbu.append(it.next() + ";");
    }
    String cookies = sbu.toString();
    cookies = cookies.substring(0, cookies.length() - 1);
    this.Cookie = cookies;
    //memcachedManager.set("PLX_" + username + "_" + password, cookies, 300);
    return cookies;
}
 
Example 2
Project: 8ComicSDK-JAVA   File: EasyHttp.java   Source Code and License Vote up 6 votes
private Response createResponse(HttpURLConnection connection,
		boolean newline) throws IOException {
	int code = connection.getResponseCode();
	InputStream inputStream = null;
	String body = null;
	String contentType = connection.getHeaderField("content-type");
	String useCharset = getCharsetFromContentType(contentType);
	
	//取reponse取得的chsetat為null時,採用預設的charset
	if(useCharset == null){
		useCharset = mReadCharset;
	}
	
	try {
		inputStream = getInputStream(connection);
		body = readString(inputStream, useCharset, newline);
	} catch (IOException e) {
		e.printStackTrace();
		inputStream = getErrorStream(connection);
		body = readString(inputStream, useCharset, newline);
	}

	return new Response(code, body, connection.getHeaderFields());
}
 
Example 3
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   Source Code and License Vote up 6 votes
static void printHttpHeaders(
    HttpURLConnection connection 
   ) {
    Map<String, List<String>> headers = connection.getHeaderFields();
    Set<String> keys = headers.keySet();
    Iterator<String> itr = keys.iterator();
    while( itr.hasNext() )
    {
    	String key = itr.next();
    	List<String> values = headers.get( key );
    	StringBuffer sb = new StringBuffer();
    	sb.append(  key ).append( ":" );
    	Iterator<String> itrV = values.iterator();
    	while( itrV.hasNext() ) sb.append( " " ).append( itrV.next() );
    	System.out.println( sb );
    }
}
 
Example 4
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   Source Code and License Vote up 6 votes
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
// Test that Cronet strips content-encoding header.
public void testStripContentEncoding() throws Exception {
    URL url = new URL(NativeTestServer.getFileURL("/gzipped.html"));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    assertEquals("foo", connection.getHeaderFieldKey(0));
    assertEquals("bar", connection.getHeaderField(0));
    assertEquals(null, connection.getHeaderField("content-encoding"));
    Map<String, List<String>> responseHeaders = connection.getHeaderFields();
    assertEquals(1, responseHeaders.size());
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    // Make sure Cronet decodes the gzipped content.
    assertEquals("Hello, World!", TestUtil.getResponseAsString(connection));
    connection.disconnect();
}
 
Example 5
Project: uavstack   File: WebHttpHelper.java   Source Code and License Vote up 6 votes
/**
 * getCookie
 * 
 * @param conn
 * @return
 */
public static String getCookie(HttpURLConnection conn) {

    Map<String, List<String>> resHeaders = conn.getHeaderFields();
    StringBuffer sBuffer = new StringBuffer();
    for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
        String name = entry.getKey();
        if (name == null)
            continue; // http/1.1 line
        List<String> values = entry.getValue();
        if (name.equalsIgnoreCase("Set-Cookie")) {
            for (String value : values) {
                if (value == null) {
                    continue;
                }
                String cookie = value.substring(0, value.indexOf(";") + 1);
                sBuffer.append(cookie);
            }
        }
    }
    if (sBuffer.length() > 0) {
        return sBuffer.toString();
    }
    return sBuffer.toString();
}
 
Example 6
Project: BiglyBT   File: ResourceUploaderURLImpl.java   Source Code and License Vote up 5 votes
protected void
getRequestProperties(
	HttpURLConnection		con )
{
	try{
		setProperty( ResourceDownloader.PR_STRING_CONTENT_TYPE, con.getContentType() );

		Map	headers = con.getHeaderFields();

		Iterator it = headers.entrySet().iterator();

		while( it.hasNext()){

			Map.Entry	entry = (Map.Entry)it.next();

			String	key = (String)entry.getKey();
			Object	val	= entry.getValue();

			if ( key != null ){

				setProperty( "URL_" + key, val );
			}
		}
	}catch( Throwable e ){

		Debug.printStackTrace(e);
	}
}
 
Example 7
Project: ChatBot   File: WebRequest.java   Source Code and License Vote up 5 votes
/**
 * Reads the raw response from a server.
 * @param connection the HttpURLConnection to read the raw response from.
 * @return The raw response from the server.
 * @throws IOException if an IOException occurs.
 */
public static synchronized String readRaw(HttpURLConnection connection) throws IOException
{
	connection.connect();
	Map<String,List<String>> headMap = connection.getHeaderFields();
	String raw = "";
	//A status line which includes the status code and reason message
	// (e.g., HTTP/1.1 200 OK).
	raw += connection.getHeaderField(null)+'\n';
	//Response header fields
	for(String head : headMap.keySet())
	{
		if(head==null)
			continue;
		raw += head + ": ";
		List<String> vals = headMap.get(head);
		//Response header field values (e.g., Content-Type: text/html).
		for(String v : vals)
			raw += v;
		raw += '\n';
	}
	//An empty line.
	raw += '\n';
	//An optional message body.
	raw += read(connection);
	return raw;
}
 
Example 8
Project: bnade-web-ssh   File: HttpUtils.java   Source Code and License Vote up 5 votes
/**
 * 通过http的HEAD方式获取url返回的http响应头
 *
 * @param url 资源URL
 * @return 响应头封装在Map中
 * @throws IOException IO异常
 */
public static Map<String, List<String>> getHeaderFields(String url) throws IOException {
	HttpURLConnection conn = null;
	try {
		conn = getHttpURLConnection(url);
		// Request Method
		conn.setRequestMethod("HEAD");
		return conn.getHeaderFields();
	} finally {
		if (conn != null) {
			conn.disconnect();
		}
	}
}
 
Example 9
Project: AndroidVideoCache   File: Response.java   Source Code and License Vote up 5 votes
public Response(HttpURLConnection connection) throws IOException {
    this.code = connection.getResponseCode();
    this.contentLength = connection.getContentLength();
    this.contentType = connection.getContentType();
    this.headers = connection.getHeaderFields();
    this.data = ByteStreams.toByteArray(connection.getInputStream());
}
 
Example 10
Project: fangcloud-java-sdk   File: StandardHttpRequestor.java   Source Code and License Vote up 5 votes
private Response toResponse(HttpURLConnection conn) throws IOException {
    int responseCode = conn.getResponseCode();
    InputStream bodyStream;
    if (responseCode >= 400 || responseCode == -1) {
        bodyStream = conn.getErrorStream();
    } else {
        bodyStream = conn.getInputStream();
    }
    interceptResponse(conn);
    return new Response(responseCode, bodyStream, conn.getHeaderFields(), conn.getContentLength());
}
 
Example 11
Project: MaximoForgeViewerPlugin   File: ForgeRS.java   Source Code and License Vote up 5 votes
@GET
   @Produces(MediaType.APPLICATION_JSON)
   @Path("bubble/{urn}/thumbnail")
   public Response bubbleThumbnail(
   	@Context HttpServletRequest request,
   	@PathParam("urn") String urn 
) 
	throws IOException, 
	       URISyntaxException 
   {
   	APIImpl impl = getAPIImpl( request );
   	if( impl == null )
   	{
           return Response.status( Response.Status.UNAUTHORIZED ).build();     
   	}
   	
   	String scope[] = { DataRESTAPI.SCOPE_VIEWABLE_READ };
   	ResultAuthentication result = impl.authenticate( scope );
   	
   	if( result.isError() )
   	{
       	return formatReturn( result );
   	}
   	
	URL url = new URL( impl.getThumbnailURL( urn ) );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "GET" );
	result.setAuthHeader( connection );
	
       int httpStatus = connection.getResponseCode();
       if( httpStatus > 299 )
       {
        return Response.status( httpStatus )
                .header("Pragma", "no-cache")
                .header("Cache-Control", "no-cache")                
                .entity( connection.getErrorStream() )
                .build();     
       }

       // Copy Autodesk headers describing thumbnail
       Map<String, List<String>> headers = connection.getHeaderFields();
       Iterator<String> itr = headers.keySet().iterator();
       Response.ResponseBuilder builder = Response.status( httpStatus );
       while( itr.hasNext() )
       {
       	String key = itr.next();
       	if( key == null ) continue;
       	if( !key.startsWith( "x-ads" )) continue;
       	String value = connection.getHeaderField( key );
       	builder.header( key, value );                
       }
       
       return builder.entity( connection.getInputStream() )
               .header("content-encoding", connection.getContentEncoding() )      
               .header("content-type", connection.getContentType() )      
               .build();     
   }
 
Example 12
Project: iosched-reader   File: HttpResponse.java   Source Code and License Vote up 5 votes
public HttpResponse(HttpURLConnection urlConnection, byte[] body) {
    try {
        this.status = urlConnection.getResponseCode();
        this.url = urlConnection.getURL().toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.headers = urlConnection.getHeaderFields();
    this.body = body;
}
 
Example 13
Project: hadoop   File: TestWebAppProxyServlet.java   Source Code and License Vote up 5 votes
private boolean isResponseCookiePresent(HttpURLConnection proxyConn, 
    String expectedName, String expectedValue) {
  Map<String, List<String>> headerFields = proxyConn.getHeaderFields();
  List<String> cookiesHeader = headerFields.get("Set-Cookie");
  if (cookiesHeader != null) {
    for (String cookie : cookiesHeader) {
      HttpCookie c = HttpCookie.parse(cookie).get(0);
      if (c.getName().equals(expectedName) 
          && c.getValue().equals(expectedValue)) {
        return true;
      }
    }
  }
  return false;
}
 
Example 14
Project: hadoop   File: AuthenticatedURL.java   Source Code and License Vote up 5 votes
/**
 * Helper method that extracts an authentication token received from a connection.
 * <p>
 * This method is used by {@link Authenticator} implementations.
 *
 * @param conn connection to extract the authentication token from.
 * @param token the authentication token.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication exception occurred.
 */
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException {
  int respCode = conn.getResponseCode();
  if (respCode == HttpURLConnection.HTTP_OK
      || respCode == HttpURLConnection.HTTP_CREATED
      || respCode == HttpURLConnection.HTTP_ACCEPTED) {
    Map<String, List<String>> headers = conn.getHeaderFields();
    List<String> cookies = headers.get("Set-Cookie");
    if (cookies != null) {
      for (String cookie : cookies) {
        if (cookie.startsWith(AUTH_COOKIE_EQ)) {
          String value = cookie.substring(AUTH_COOKIE_EQ.length());
          int separator = value.indexOf(";");
          if (separator > -1) {
            value = value.substring(0, separator);
          }
          if (value.length() > 0) {
            token.set(value);
          }
        }
      }
    }
  } else {
    token.set(null);
    throw new AuthenticationException("Authentication failed, status: " + conn.getResponseCode() +
                                      ", message: " + conn.getResponseMessage());
  }
}
 
Example 15
Project: GitHub   File: JavaApiConverter.java   Source Code and License Vote up 4 votes
/**
 * Extracts OkHttp headers from the supplied {@link java.net.HttpURLConnection}. Only real headers
 * are extracted. See {@link #extractStatusLine(java.net.HttpURLConnection)}.
 */
private static Headers extractOkResponseHeaders(
    HttpURLConnection httpUrlConnection, Response.Builder okResponseBuilder) {
  Map<String, List<String>> javaResponseHeaders = httpUrlConnection.getHeaderFields();
  return extractOkHeaders(javaResponseHeaders, okResponseBuilder);
}
 
Example 16
Project: GitHub   File: CacheAdapterTest.java   Source Code and License Vote up 4 votes
private void executeGet(HttpURLConnection connection) throws IOException {
  connection.connect();
  connection.getHeaderFields();
  connection.disconnect();
}
 
Example 17
Project: GitHub   File: JavaApiConverter.java   Source Code and License Vote up 4 votes
/**
 * Extracts OkHttp headers from the supplied {@link java.net.HttpURLConnection}. Only real headers
 * are extracted. See {@link #extractStatusLine(java.net.HttpURLConnection)}.
 */
private static Headers extractOkResponseHeaders(
    HttpURLConnection httpUrlConnection, Response.Builder okResponseBuilder) {
  Map<String, List<String>> javaResponseHeaders = httpUrlConnection.getHeaderFields();
  return extractOkHeaders(javaResponseHeaders, okResponseBuilder);
}
 
Example 18
Project: labtablet   File: DendroAPI.java   Source Code and License Vote up 4 votes
public static String authenticate(Context context) throws Exception{

        DendroConfiguration conf = FileMgr.getDendroConf(context);


        URL url = new URL(conf.getAddress() + "/login");

        final String COOKIES_HEADER = "Set-Cookie";

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setRequestProperty("Accept","application/json");
        conn.setDoOutput(true);

        System.out.println(conn.getRequestProperties().toString());

        JSONObject json = new JSONObject();
        json.put("username", conf.getUsername());
        json.put("password", conf.getPassword());

        OutputStream os = conn.getOutputStream();
        os.write(json.toString().getBytes());
        os.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        StringBuilder response = new StringBuilder();
        while ((output = br.readLine()) != null) {
            response.append(output);
            response.append('\r');
        }
        String mes = response.toString();
        conn.disconnect();

        AsyncUploader.DendroResponse loginResponse = new Gson().fromJson(mes, AsyncUploader.DendroResponse.class);

        if (loginResponse.result.equals(Utils.DENDRO_RESPONSE_ERROR)) {
            Log.e("AUTH", loginResponse.result + ": " + loginResponse.message);
            throw new Exception(loginResponse.result + ": " + loginResponse.message);
        }

        CookieManager msCookieManager = new CookieManager();
        Map<String, List<String>> headerFields = conn.getHeaderFields();
        List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

        if (cookiesHeader != null) {
            for (String cookie : cookiesHeader) {
                msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }
        }

        return msCookieManager.getCookieStore().getCookies().get(0).toString();
    }
 
Example 19
Project: Shared-Route   File: CommonHttp.java   Source Code and License Vote up 4 votes
public static String postGetJson(String url, String content) {
        try {
            URL mUrl = new URL(url);
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            //设置链接超时时间
            mHttpURLConnection.setConnectTimeout(15000);
            //设置读取超时时间
            mHttpURLConnection.setReadTimeout(15000);
            //设置请求参数
            mHttpURLConnection.setRequestMethod("POST");
            //添加Header
            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            //接收输入流
            mHttpURLConnection.setDoInput(true);
            //传递参数时需要开启
            mHttpURLConnection.setDoOutput(true);
            //Post方式不能缓存,需手动设置为false
            mHttpURLConnection.setUseCaches(false);

            mHttpURLConnection.connect();

            DataOutputStream dos = new DataOutputStream(mHttpURLConnection.getOutputStream());

            String postContent = content;

            dos.write(postContent.getBytes());
            dos.flush();
            // 执行完dos.close()后,POST请求结束
            dos.close();
            // 获取代码返回值
            int respondCode = mHttpURLConnection.getResponseCode();
            Log.d("respondCode","respondCode="+respondCode );
            // 获取返回内容类型
            String type = mHttpURLConnection.getContentType();
            Log.d("type", "type="+type);
            // 获取返回内容的字符编码
            String encoding = mHttpURLConnection.getContentEncoding();
            Log.d("encoding", "encoding="+encoding);
            // 获取返回内容长度,单位字节
            int length = mHttpURLConnection.getContentLength();
            Log.d("length", "length=" + length);
//            // 获取头信息的Key
//            String key = mHttpURLConnection.getHeaderField(idx);
//            Log.d("key", "key="+key);
            // 获取完整的头信息Map
            Map<String, List<String>> map = mHttpURLConnection.getHeaderFields();
            if (respondCode == 200) {
                // 获取响应的输入流对象
                InputStream is = mHttpURLConnection.getInputStream();
                // 创建字节输出流对象
                ByteArrayOutputStream message = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    message.write(buffer, 0, len);
                }
                // 释放资源
                is.close();
                message.close();
                // 返回字符串
                String msg = new String(message.toByteArray());
                Log.d("Common", msg);
                return msg;
            }
            return "fail";
        }catch(Exception e){
            return "error";
        }
    }
 
Example 20
Project: PangciACG   File: Client.java   Source Code and License Vote up 4 votes
private String doPost(String apiCat, String api, Map<String, String> params) {
    // 组合链接
    String apiUrl = Config.API_ROOT + apiCat + '/' + api + '/';
    if (Config.KEEP_SECRET) {
        apiUrl += "&mobile_sign=" + getSign(apiCat);
    }
    Log.d("POST", apiUrl);
    // 建立请求内容
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey())
                .append("=")
                .append(URLEncoder.encode(entry.getValue()))
                .append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // 发出请求
    try {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // 附上Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // 发送请求内容
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // 接收返回信息
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // 保存Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // 处理返回的字符串流
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            return new String(byteArrayOutputStream.toByteArray());
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}